Mar*_*Him 33 objective-c uibutton uilabel ios swift
我想确保按钮文本适合UIButton,而UIButton具有固定大小.
当然我可以访问UIButton的titleLabel.在标签中,我将设置autoshrink
为最小字体比例,似乎对应于
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
Run Code Online (Sandbox Code Playgroud)
,但实际上表现不一样,因为它只使文本水平地适合边界而不是垂直,从而不会改变字体大小.
如何以编程方式实际调整标签的字体大小以使文本适合标签边界(如下图中的 目标 所示)?
我已经试过了
self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;
Run Code Online (Sandbox Code Playgroud)
没有成功,总是像adjustsFontSizeToFitWidth
上面的图片左侧那样结束.
编辑:解决方案还必须符合ios7
Mar*_*Him 80
self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0; <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
Run Code Online (Sandbox Code Playgroud)
...在viewDidLoad中的layoutIfNeeded之后做了诀窍事实证明,所有这些都必须设置为实际调整字体大小,而不仅仅是让它适合框架.
mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0 <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
Run Code Online (Sandbox Code Playgroud)
更新了Swift 3.0的代码:
yourButton.titleLabel?.minimumScaleFactor = 0.5
yourButton.titleLabel?.numberOfLines = 0
yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
Run Code Online (Sandbox Code Playgroud)
您还可以在Interface Builder中为按钮设置用户定义的运行时属性
titleLabel.adjustsFontSizeToFitWidth = true
Run Code Online (Sandbox Code Playgroud)
使文本水平和垂直适合按钮边界:
1 - 像图像一样设置按钮对齐(* 非常重要 *)
2 - 在您的 ViewController 中添加这行代码
btnTest.setTitle("Test for multi line in button show line in button show Test for multi line in button show line in button show", for: .normal)
btnTest.titleLabel!.textAlignment = .center
btnTest.titleLabel!.numberOfLines = 0
btnTest.titleLabel!.adjustsFontSizeToFitWidth = true
btnTest.titleLabel!.minimumScaleFactor = 0.5
// below line to add some inset for text to look better
// you can delete or change that
btnTest.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
Run Code Online (Sandbox Code Playgroud)
btnTest.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping
在您的代码中使用或其他 BreakMode。用于在按钮中启用多行。只是使用上面的代码最后结果 :
归档时间: |
|
查看次数: |
28985 次 |
最近记录: |