我有一个大小为50x50的UIButton。如何将titleLable的字体大小设置为小于AdjustFontSizeToFitWidth创建的大小,以使字体大小适合诸如UIButton大小为50x50的自定义框架(如30x30)?
let but:UIButton = UIButton(frame: CGRect(x: 80, y: 80, width: 70, height: 50))
view.addSubview(but)
but.backgroundColor = .white
but.titleLabel?.backgroundColor = .green
but.setTitle("hello", for: .normal)
but.setTitleColor(.red, for: .normal)
//this gives the second image, still having the text uncentered.
//but.contentVerticalAlignment = .fill
but.titleLabel?.font = UIFont(name: "WarsawGothicSuExt", size: 60)
but.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
but.titleLabel?.adjustsFontSizeToFitWidth = true
but.layoutIfNeeded()
答案 0 :(得分:1)
您添加了一个内容插图,该插图定义了按钮边界与其内容边界之间的边距:
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.layoutIfNeeded()
print(button.bounds) // (0, 0, 50, 50)
print(button.titleLabel?.bounds) // (0, 0, 30, 18)
您不需要致电layoutIfNeeded()
。它包含在其中,可以使按钮立即自动更新,以便我们获取边界矩形。