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?

I figured out the fix which involved setting the button's Style to default instead of Plain.
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:
button.configuration = .plain()
And setting the title in the storyboard would set the title of the configuration, rather than calling setTitle(_:for:). You can think of this as:
button.configuration?.title = "..."
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 using button.configuration?.title.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With