'Why do certain ways of getting a button's title not work?
I'm trying to get the title of a UIButton. The docs mentioned a few different ways of doing this, so I tried out a few of them with mixed results.
I dropped a button on the canvas (I'm using Storyboard, not SwiftUI), connected it to an IBAction, and tested out getting the title with the following code:
@IBAction func printTitle(_ sender: UIButton) {
if let buttonTitle = sender.titleLabel?.text {
print("title label text:", buttonTitle)
} else {
print("Title label text doesn't exist")
}
if let buttonTitle = sender.configuration?.title {
print("configuration title:", buttonTitle)
} else {
print("configuration title doesn't exist")
}
if let buttonTitle = sender.currentTitle {
print("current title:", buttonTitle)
} else {
print("Current title doesn't exist")
}
if let buttonTitle = sender.title(for: .normal) {
print("title for normal state:", buttonTitle)
} else {
print("Title for normal state doesn't exist")
}
if let buttonTitle = sender.title(for: .selected) {
print("title for selected state:", buttonTitle)
} else {
print("Title for selected state doesn't exist")
}
if let buttonTitle = sender.title(for: .highlighted) {
print("title for highlighted state:", buttonTitle)
} else {
print("Title for highlighted state doesn't exist")
}
}
After clicking the button, I end up getting the following output (the button's title is 'Hello'):
title label text: Hello
configuration title: Hello
Current title doesn't exist
Title for normal state doesn't exist
Title for selected state doesn't exist
Title for highlighted state doesn't exist
I tested this out with a few different built-in button types (System and Detail Disclosure) and the same thing happens. Why does the title(for:) method and the currentTitle property not work? What is the best way to get a button's title?
Here is a link to an Xcode project with just the button and the IBAction above in ViewController.swift: https://github.com/msotoTTP/test1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
