I'm just learning how to build apps using Swift and Xcode. I'm following along through the Xcode Fundamentals book, and ran into an issue in the "Apple Pie" project. When you tap a button, the button is supposed to reference the button title and set a variable to the button title, but the title instead comes through as "nil" and the app crashes, even though a title is set in interface builder.
I created a basic new app to test how I think this code should be working - see screenshots.
When the button (title: Aaron) is tapped, the console should print the button title, but instead I'm getting the "nil" value. What am I missing here?
That confirms that the reason is that the button is not in normal state and that its title for normal state is not defined. Which is surprising.
Which version of Xcode do you use ?
Could you do another test by printing in the IBAction:
print("normal", sender.title(for: .normal))
print("highlighted", sender.title(for: .highlighted))
print("disabled", sender.title(for: .disabled))
print("selected", sender.title(for: .selected))
print("focused", sender.title(for: .focused))
I tested with the same button definition (Style plain). It works and the sender button content is the same as yours:
<UIButton: 0x7fa72e70b990; frame = (99 664; 214 34.3333); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x600003c315e0>> configuration=<UIButtonConfiguration: 0x600000073100> baseStyle=plain macStyle=automatic buttonSize=medium cornerStyle=dynamic title=<0x600003c31760>:'Aaron' contentInsets=default imagePlacement=leading imagePadding=0 titlePadding=1 titleAlignment=automatic automaticallyUpdateForSelection background=<UIBackgroundConfiguration: 0x60000096b300; Base Style = Custom; cornerRadius = 5.95; backgroundColor = UIExtendedGrayColorSpace 0 0>
Could you test with a default style for button, instead of plain ?