调整文本的字体大小以适应

调整文本的字体大小以适应

本文介绍了调整文本的字体大小以适应 UIButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保按钮文本适合 UIButton,而 UIButton 具有固定大小.

I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.

当然我可以访问 UIButton 的 titleLabel.在标签中,我会将 autoshrink 设置为似乎对应于

Of course I can access the titleLabel of the UIButton.In a label I would set autoshrink to minimum font scale which seems to correspond to

self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;

,但实际上并不相同,因为它只会使文本水平适应边界,而不是垂直适应,因此不会改变字体大小.

, but doesn't really behave the same, since it only makes the text fits horizontally into the bounds, not vertically, thereby not changing the font size.

如何以编程方式实际调整标签的字体大小以使文本适合标签边界(如下图的目标所示)?

How can i actually adjust the font size of a label programmatically to make the text fit into the label bounds (as shown in Goal in the picture below) ?

我已经试过了

self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;

没有成功,总是以上图左侧的 adjustsFontSizeToFitWidth 结束.

without success, always ended up as in adjustsFontSizeToFitWidth on the left side of the pic above.

编辑:解决方案还必须兼容 ios7

推荐答案

self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0;   <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;

... 在 vi​​ewDidLoad 中 layoutIfNeeded 之后成功了事实证明,所有这些都必须设置为实际调整字体大小,而不仅仅是使其适合框架.

... did the trick, after layoutIfNeeded in viewDidLoadAs it turns out, all those must be set to actually adjust the font-size, not just making it fit into the frame.

mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0   <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true

这篇关于调整文本的字体大小以适应 UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:26