Button elements that encompass multi-state semantics are quite common on iOS. We can find many examples of such just from some of Apple's first party apps on iOS, such as buttons that manage download of podcast episodes and albums in Podcast and Music, respectively.
Here we present an implementation of such button element tailored for SwiftUI, with customizability designed in mind.
Here's a demo of a scenario that simulates a download button in action.
There are three things needed to implement a multi-state button.
- Define all possible states of the semantics, as well as a view model for the button.
- Define an appearance for each possible semantics state.
- Define the element in your SwiftUI view.
The first step is to define a view model that conforms to the MultiStateButtonViewModelProtocol
protocol (defined here).
One of the associated types of the protocol is the State
type, which needs to encompass
all possible states of the semantics of the button.
Each state needs to map to a type that conforms to PrimitiveButtonStyle
(see here),
which is defined in SwiftUI that describes a type that applies custom interaction behavior
and a custom appearance to the button.
There are many predefined button styles already defined in SwiftUI. It is your choice to either use one of the predefined button styles or define your own.
Once you have all the states mapped, the view model defined and all button styles defined,
the last step is to simply plugging those into MultiStateButton
(defined here) and have it defined in your SwiftUI view that consumes the button.
Check out the demo app to see an example of how to define and customize such a multi-state button.
This project is licensed under the MIT License.
Copyright 2024 Will Li.