Swift UIButton文本未显示
我试图创建UIButton并在其中显示文本,以及指定字体大小,但它不会显示在我的故事板中,使用setTitleColor和titleLabel!。如果我将这两行注释掉并取消注释遗忘的.setTitle(当前已注释掉),它将起作用,但是我无法设置UIButton文本fontsize。有什么建议吗?我已将子视图添加到viewdidload中的视图中Swift UIButton文本未显示,swift,text,colors,uibutton,Swift,Text,Colors,Uibutton,我试图创建UIButton并在其中显示文本,以及指定字体大小,但它不会显示在我的故事板中,使用setTitleColor和titleLabel!。如果我将这两行注释掉并取消注释遗忘的.setTitle(当前已注释掉),它将起作用,但是我无法设置UIButton文本fontsize。有什么建议吗?我已将子视图添加到viewdidload中的视图中 let forgotPassword: UIButton = { let forgot = UIButton() forgot.tran
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
}()
按钮不可见,因为它没有文本 这里的问题是,这两行实际上并不设置文本,只设置外观
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)
您需要取消对设置标题的行的注释-如果没有标题,则不会显示任何内容也就不足为奇了。您还需要更改字体行-
名称
是指字体的名称,而不是要显示的文本字符串。以下工作:
let button = UIButton()
button.setTitle("Forgot your password?", for: .normal)
button.sizeToFit()
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.setTitleColor(.white, for: .normal)