为什么 .title(for: .normal) return nil 对于 UIKit 中的普通样式

Why does .title(for: .normal) return nil for Plain styles in UIKit

我正在关注 Apple Develop in Swift Fundamentals 书中的 Apple Pie 项目(第 333 - 362 页)。出现奇怪的错误,获取按钮的标题似乎导致异常。

"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())
}

我找到了解决方法,其中涉及将按钮的 Style 设置为默认值而不是 Plain。但是,我不明白为什么 Plain 样式首先会 return nil。有什么想法吗?

I figured out the fix which involved setting the button's Style to default instead of Plain.

我认为这是因为当您将样式设置为“普通”时,您实际上是在使用 UIButton.Configuration API 中介绍的 iOS 15。您基本上是在做类似的事情这个:

button.configuration = .plain()

并且在故事板中设置标题会设置 configurationtitle,而不是调用 setTitle(_:for:)。您可以将其视为:

 button.configuration?.title = "..."

这就是为什么您无法使用 title(for:) 获取标题,但您应该可以使用 button.configuration?.title.

获取您在故事板中设置的标题