Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

enter image description here

like image 987
Paul Avatar asked Oct 27 '25 05:10

Paul


1 Answers

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.

like image 142
Sweeper Avatar answered Oct 29 '25 21:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!