【问题标题】:UIButton text not showing upUIButton 文本未显示
【发布时间】:2020-03-11 02:47:55
【问题描述】:

我正在尝试使用 setTitleColor 和 titleLabel! 创建 UIButton 并在其中显示文本,以及指定字体大小,但它不会显示在我的 Storyboard 中。如果我将这两行注释掉并取消注释 forgot.setTitle (当前已注释掉),它将起作用,但是我无法设置 UIButton 文本字体大小。有什么建议?我已在 viewdidload 中将子视图添加到我的视图中。

let forgotPassword: UIButton = {
    let forgot = UIButton()
    forgot.translatesAutoresizingMaskIntoConstraints = false
    //forgot.setTitle("Forgot your password?", for: .normal)

    forgot.titleLabel! .font = UIFont(name:"Forgot your password?", size: 14)
    forgot.setTitleColor(.white, for: .normal)

    forgot.addTarget(self, action: #selector(forgot(_ :)), for: .touchUpInside)
    forgot.sizeToFit()

    //forgot.backgroundColor = .orange
    return forgot

}() 

【问题讨论】:

    标签: swift text colors uibutton


    【解决方案1】:

    您需要取消对设置标题的行的注释 - 没有标题,什么都没有出现也就不足为奇了。您还需要更改字体行 - name 是字体的名称,而不是要显示的文本字符串。以下工作:

    let button = UIButton()
    button.setTitle("Forgot your password?", for: .normal)
    button.sizeToFit()
    button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
    button.setTitleColor(.white, for: .normal)
    

    【讨论】:

      【解决方案2】:

      该按钮不可见,因为它没有文本。

      这里的问题是这两行实际上并没有设置文字,只设置了外观。

      forgot.titleLabel!.font = UIFont(name: "System", size: 14) // This is the font, not the text itself
      forgot.setTitleColor(.white, for: .normal)
      

      您也必须调用此行才能实际设置要显示的任何文本。

      forgot.setTitle("Forgot your password?", for: .normal)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-16
        • 2011-11-30
        • 1970-01-01
        • 2012-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多