Swift
UIButton
Programming
iOS Development
Code Change

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.

Introduction

In iOS app development, UIKit provides a flexible and powerful way to manage user interfaces. One fundamental component available in UIKit is the UIButton. A UIButton is a customizable button that developers can use to handle user interactions. One common modification developers might need to make is changing the text of a UIButton programmatically. This simple adjustment can enhance the app's interactivity and responsiveness to user actions or changes in app state.

UIButton Overview

UIButton is a subclass of UIControl, which in turn inherits from UIView. It is designed to easily receive touch events, and it can be visually customized in numerous ways. Some key properties of UIButton include its title, background color, and image. In this article, we'll primarily focus on modifying the button's title.

Changing UIButton Text

To change the text of a UIButton programmatically, you can use the setTitle(_:for:) method. This method allows you to set the title for different states of the button, such as normal, highlighted, disabled, or selected.

Syntax

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

Explanation

  • button: An instance of UIButton.
  • "New Title": The new text you want to display on the button.
  • .normal: The state of the button for which you want to set the title. Common states include normal, highlighted, disabled, and selected.

Practical Examples

Let's look at some practical scenarios where you might want to change a button's text programmatically:

Example 1: Toggle Button

Suppose you want a button that toggles between "Start" and "Stop". You can easily achieve this by changing the button's title when the button is tapped.

swift
1@IBOutlet weak var toggleButton: UIButton!
2
3@IBAction func buttonTapped(_ sender: UIButton) {
4    let currentTitle = sender.title(for: .normal)
5    let newTitle = (currentTitle == "Start") ? "Stop" : "Start"
6    sender.setTitle(newTitle, for: .normal)
7}

Example 2: Localized Button Titles

In internationalized apps, you might want to change the button text according to the user's language settings. This is similar to doing it in Android with resources and can be achieved using string localization in Swift.

swift
1let currentLanguage = Locale.current.languageCode
2let startText = NSLocalizedString("Start", comment: "Start button title")
3let stopText = NSLocalizedString("Stop", comment: "Stop button title")
4
5button.setTitle((currentLanguage == "en") ? startText : stopText, for: .normal)

Summary Table

Below is a summary of changing the UIButton title programmatically:

ComponentDescription
MethodsetTitle(_:for:)
Parameter 1New title as a String
Parameter 2State (e.g., .normal, .highlighted)
Toggle ExampleChanges title between "Start" and "Stop" through logic.
LocalizationUses NSLocalizedString for changing button titles across localization.
BenefitsEnhances app interactivity and responsiveness.

Advanced Topics

Dynamic Button Titles

You can further enhance button functionality by using dynamic data to set button titles. For instance, if you're loading data from a network, you might update the button title based on the response.

swift
1func fetchData() {
2    NetworkManager.fetch { result in
3        switch result {
4        case .success(let data):
5            self.button.setTitle("Success: \(data.count)", for: .normal)
6        case .failure:
7            self.button.setTitle("Retry", for: .normal)
8        }
9    }
10}

Button Title with Attributes

To add style to the text, such as changing font size or color, use NSAttributedString.

swift
1let attributes: [NSAttributedString.Key: Any] = [
2    .font: UIFont.boldSystemFont(ofSize: 18),
3    .foregroundColor: UIColor.blue
4]
5
6let attributedTitle = NSAttributedString(string: "Custom Title", attributes: attributes)
7button.setAttributedTitle(attributedTitle, for: .normal)

Conclusion

Changing the text of a UIButton programmatically is a straightforward yet powerful feature that can elevate the user experience by making the interface dynamic and responsive. By understanding how to manipulate button titles, you gain deeper control over your app's UI, allowing you to react to user interactions and application states effectively.


Course illustration
Course illustration

All Rights Reserved.