按钮不可见,因为它没有文本。
我正在尝试创建UIButton并在其中显示文本,以及指定字体大小,但它不会显示在我的情节提要中,使用setTitleColor和titleLabel!。如果我将这2行注释掉并取消注释前面的.setTitle(当前已注释掉(,它会起作用,但这样我就无法设置UIButton文本字体大小。有什么建议吗?我已在我的视图didload中将子视图添加到我的视图中。
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
}()
您需要取消对设置标题的行的注释-如果没有标题,则不会出现任何结果也就不足为奇了。您还需要更改字体行——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)
这里的问题是,这两行实际上并没有设置文本,只有外观。
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)