ios - UIButton 的 titleLabel 是可选的原因是什么?

标签 ios swift uibutton

UIButton 的 titleLabel 是可选的原因是什么?

通过放置感叹号来隐式解开此选项是否安全?如果不是,当 titleLabel 为 nil 时会出现什么情况?

顺便说一句,我使用 UIButton.titleLabel 来更改无法从 UIButton 直接访问的 UILabel 属性,例如更改字体或多行标签。

最佳答案

最佳实践不是强制展开,但您几乎可以保证 UIButton.titleLabel 在您需要时存在。我不是 100% 确定语法,但它是某种形式的延迟加载,而不是 lazy var titleLabel:UILabel = {}()

就我个人而言,如果您担心展开,我会使用 guardif let

guard let label = myButton.titleLabel else {return}
label.font = .systemFontOfSize(10.0)

if let label = myButton.titleLabel { label.font = .systemFontOfSize(10.0) }

关于ios - UIButton 的 titleLabel 是可选的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40675124/

相关文章:

ios - 如何在WKWebview中添加观察者来播放和暂停音频文件的 Action ?

ios - 为什么数据不在 View Controller 之间传递? swift 3

swift - Swift 中的可变字符串

ios - 使用 reloadRowsAtIndexPaths 或 reloadSections 导致 Tableview Cell 闪烁

ios - 当配置文件过期时会发生什么?

ios - 关联类型的依赖注入(inject)导致 Swift 中没有类型名称(下划线)的参数

swift - 'RLMException',原因 : 'Opening Realm files of format version 11 is not supported by this version of Realm'

ios - 内部修饰 (@IBAction) 不适用于 UIButton 子类

swift - 是否有一个函数可以用来查找按下了哪个 UIButton 并返回 true 或 false?

ios - Segue延迟UIButton高亮显示