为什么 .title(for: .normal) 对于 UIKit 中的 Plain 样式返回 nil
我正在关注 Apple 的 使用 Swift 基础知识进行开发的 Apple Pie 项目 书(第 333 - 362 页)。有一个奇怪的错误,获取按钮的标题似乎会导致异常。
“致命错误:展开可选值时意外发现 nil”
@IBAction func letterButtonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)! <-- offending code
let letter = Character(letterString.lowercased())
}
我找到了修复方法,其中涉及将按钮的 Style
设置为默认值,而不是 Plain
。但是,我不明白为什么 Plain
样式首先会返回 nil。有什么想法吗?
I'm following the Apple Pie project from Apple's Develop in Swift Fundamentals book (pp. 333 - 362). There was a weird error where getting a button's title seemed to cause an exception.
"Fatal error: Unexpectedly found nil while unwrapping an Optional value"
@IBAction func letterButtonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)! <-- offending code
let letter = Character(letterString.lowercased())
}
I figured out the fix which involved setting the button's Style
to default instead of Plain
. However, I don't understand why the Plain
style would return nil in the first place. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是因为当您将样式设置为“Plain”时,您实际上是在使用
UIButton.Configuration
API 在 iOS 15 中引入。您基本上在做类似这样的事情:在情节提要中设置标题将设置故事板的
title
configuration
,而不是调用setTitle(_:for:)
。您可以将其视为:这就是为什么您无法使用
title(for:)
获取标题,但您应该能够使用button 获取您在情节提要中设置的标题.配置?.标题
。I think this is because when you set the style to "Plain", you are effectively using the
UIButton.Configuration
API introduced in iOS 15. You are basically doing something like this:And setting the title in the storyboard would set the
title
of theconfiguration
, rather than callingsetTitle(_:for:)
. You can think of this as:This is why you can't get the title using
title(for:)
, but you should be able to get the title you set in the storyboard usingbutton.configuration?.title
.