Sometimes, we would require a button to show a loader with appropriate text when a long-duration task is done, such as downloading an image. Before iOS 15, we had to write a custom button or do some hacks to show a simple loader or an UIActivityIndicator inside an UIButton. Now, it is not the case anymore. UIButtonConfiguration provides showsActivityIndicator, a simple property using which we can hide/show a loader inside a button.

We recommend that you visit this article if you are unfamiliar with UIButtonConfiguration.

To hide the loader or activity indicator

var configuration = UIButton.Configuration.filled()
configuration.showsActivityIndicator = false

To hide the loader or activity indicator in a UIButton

To show the loader or activity indicator

var configuration = UIButton.Configuration.filled()
configuration.showsActivityIndicator = true

To show the loader or activity indicator in a UIButton

Customizing the color of the loader or activity indicator

We can also customize the color of the loader or activity indicator by using the UIConfigurationColorTransformer.

We can use two options: choose the default ones (grayscale, preferredTint, or monochromeTint) or use our custom color.

Default color usage

var configuration = UIButton.Configuration.filled()
configuration.activityIndicatorColorTransformer = UIConfigurationColorTransformer.preferredTint

Custom color usage

var configuration = UIButton.Configuration.filled()
configuration.activityIndicatorColorTransformer = UIConfigurationColorTransformer({ _ in
    return .systemYellow
})

The UIButton provides us a configurationUpdateHandler where we can change the button’s appearance using the configuration. The configurationUpdateHandler is triggered when the setNeedsUpdateConfiguration method is called on the button.

var  shouldToggleActivityIndicator: Bool = false {
    didSet {
        self.button.setNeedsUpdateConfiguration()
    }
}

private  func  configureButton() {
    var configuration = UIButton.Configuration.filled()
    configuration.title = "Download"
    configuration.showsActivityIndicator = false
    button = UIButton(configuration: configuration, primaryAction: UIAction { _ in
        self.shouldToggleActivityIndicator.toggle()
    })
    button.configurationUpdateHandler = { button in
        var config = button.configuration
        if  self.shouldToggleActivityIndicator == true {
            config?.title = "Downloading"
        }else {
            config?.title = "Download"
        }
        config?.showsActivityIndicator = self.shouldToggleActivityIndicator
        config?.activityIndicatorColorTransformer = UIConfigurationColorTransformer({ _ in
            return .systemYellow
        })
        button.configuration = config
    }
}

References

[1] https://developer.apple.com/documentation/uikit/uibutton/configuration

About the author

Support creators