调整文字的字体大小以适应UIButton
我想确保button文本适合于UIButton,而UIButton具有固定的大小。
当然,我可以访问UIButton的titleLabel。 在一个标签,我会设置autoshrink
最小的字体规模,这似乎对应
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
,但实际上并不相同,因为它只能使文本水平地embedded边界而不是垂直,从而不会改变字体大小。
我如何实际调整标签的字体大小以使文本适合标签边界(如下图所示)?
我已经尝试过了
self.myButton.titleLabel.numberOfLines = 0; self.myButton.titleLabel.minimumScaleFactor = 0.5f;
如果没有成功,总是会在adjustsFontSizeToFitWidth
左侧的adjustsFontSizeToFitWidth
。
编辑 : 解决scheme也必须符合ios7
self.mybutton.titleLabel.minimumScaleFactor = 0.5f; self.mybutton.titleLabel.numberOfLines = 0; <-- Or to desired number of lines self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
…在layoutIfNeeded之后,在viewDidLoad之后做了诀窍事实certificate,所有这些都必须设置为实际调整字体大小,而不是使其适合框架。
Swift 3的更新:
mybutton.titleLabel?.minimumScaleFactor = 0.5 mybutton.titleLabel?.numberOfLines = 0 <-- Or to desired number of lines mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
尝试调用以下方法。
button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters
Swift 3.0的更新代码:
yourButton.titleLabel?.minimumScaleFactor = 0.5 yourButton.titleLabel?.numberOfLines = 0 yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
尝试这个:
[myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]]; textWidth = [text sizeWithFont:[myButton font]].width; }
您还可以在Interface Builder中为“buttonLabel.adjustsFontSizeToFitWidth”= true的button设置用户定义的运行时属性
在Xcode->打开故事板 – >去属性检查器 – >控制 – >alignment – >水平和垂直select第二。
要么
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
在你的代码之后写下这行:
yourButton.SizeToFitWidth=YES;
如果你喜欢在故事板上做,只需点击button,然后显示属性检查器,并将换行符设置为“Word Wrap”。