【问题标题】:Swift how do you fit font size to custom frame?Swift 如何让字体大小适合自定义框架?
【发布时间】:2019-01-24 00:34:57
【问题描述】:

我有一个大小为 50x50 的 UIButton。如何将 titleLable 的字体大小设置为小于 adjustFontSizeToFitWidth 创建的大小,以便字体大小适合让我们说像 30x30 这样的自定义框架,而 UIButton 的大小是 50x50?

    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()

【问题讨论】:

    标签: swift uibutton font-size


    【解决方案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()。它包含在此处以使按钮立即更新,以便我们可以获得边界矩形。

    【讨论】:

    • 太棒了,我不知道。但我遇到了另一个问题。你会让字体的初始大小是多少?如果我把它做得太小,它会很好地适应按钮,但 adjustsFontSizeToFitWidth 和 UIEdgeInserts 不会做任何事情来使它很好地适应按钮。另一方面,如果我让字体太大,titleLable 的高度就会成为问题(将文本推到底部而不是在按钮上居中)。我用示例代码和我得到的内容编辑了我的问题。
    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多