Swift
UIButton
iOS Development
Programming
Code Example

Changing text of UIButton programmatically swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

To change the text of a UIButton programmatically in Swift, you can use the setTitle(_:for:) method provided by the UIButton class. This method allows you to set the title (text) for different states that a button can have. In this article, we'll explore the specifics of modifying the text of a UIButton, including technical explanations, examples, and additional insights to help you fully understand the process.

Understanding UIButton States

A UIButton can have several states, each potentially showing different text. Here are the main states:

  • .normal: The default state of the button.
  • .highlighted: When the button is pressed.
  • .disabled: When the button is inactive.
  • .selected: When the button is selected.

By specifying the state, you ensure that the button displays the appropriate text under various conditions.

Changing UIButton Text

To change the text of a UIButton for its normal state, you can use the following Swift code:

swift
button.setTitle("New Title", for: .normal)

Example

Suppose you have a button, and you want to update its text when the user taps another button. Here's how you might achieve this:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    let myButton: UIButton = {
5        let button = UIButton(type: .system)
6        button.setTitle("Original Title", for: .normal)
7        return button
8    }()
9
10    override func viewDidLoad() {
11        super.viewDidLoad()
12        view.addSubview(myButton)
13        // Call changeTitle() when needed, e.g., on another button tap
14    }
15
16    func changeTitle() {
17        myButton.setTitle("New Title", for: .normal)
18    }
19}

Explanation

In the above example:

  • We've initialized a button with an original title "Original Title".
  • The changeTitle function is called to update the button's title to "New Title".
  • This exemplifies how to target the normal state of the button.

Advanced Usage

For more advanced scenarios, you might want to change the button's title based on other states. Here's how you can address this:

swift
button.setTitle("Highlighted Title", for: .highlighted)
button.setTitle("Disabled Title", for: .disabled)
button.setTitle("Selected Title", for: .selected)

Dynamic and Localized Text

If your app supports multiple languages, you might want to localize button texts. You can achieve this with NSLocalizedString as shown:

swift
let localizedTitle = NSLocalizedString("button_title_key", comment: "")
button.setTitle(localizedTitle, for: .normal)

This makes use of a Localizable.strings file to provide translations for different languages.

Programmatically Creating Buttons

Often, you might find yourself required to create buttons programmatically rather than using Interface Builder. Here's a concise guide to doing so:

  1. Initialization: Use UIButton(type:) initializer.
  2. Set Properties: Customize properties such as font, color, background.
  3. Constraints: Establish constraints programmatically using Auto Layout.
swift
1let programmaticButton = UIButton(type: .system)
2programmaticButton.setTitle("Tap me", for: .normal)
3programmaticButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
4programmaticButton.frame = CGRect(x: 50, y: 100, width: 200, height: 50) // Temporary layout example
5view.addSubview(programmaticButton)

Key Points

Here's a summary of what you've learned:

FeatureDescription
setTitle(_:for:)Method to change button title for specified state.
Button States.normal, .highlighted, .disabled, .selected
LocalizationUse NSLocalizedString for multilingual support.
Programmatic CreationInitialize and configure programmatically.
Dynamic Text UpdatesUpdates based on user actions or other triggers.

Conclusion

Changing the text of a UIButton programmatically in Swift is a straightforward task given Swift’s robust API provided by UIKit. By understanding button states and combining UI updates with localization and programmatic UI management, you can create versatile and responsive applications.

When designing UI, always consider the various states a button might be in and dynamically attribute titles accordingly to ensure a seamless and intuitive user experience. This adaptability plays a crucial role in creating polished applications that can cater to diverse user interfaces and languages.


Course illustration
Course illustration

All Rights Reserved.