Disable a Button in SwiftUI
Written by Team Kodeco
Buttons are an essential part of any user interface. However, sometimes you may want to temporarily disable a button to prevent users from taking actions that are not allowed. SwiftUI makes it easy to manage the disabled state of buttons.
In the following example, you’ll create a simple button, disable it and then dynamically enable or disable it based on certain conditions:
struct ContentView: View {
@State private var isButtonDisabled = true
var body: some View {
VStack {
Button("Tap me") {
print("Button tapped")
}
.disabled(isButtonDisabled)
Button("\(isButtonDisabled ? "Enable" : "Disable") button") {
isButtonDisabled.toggle()
}
.padding()
}
}
}
Tap Enable button once and your preview should look like this:
This code does the following:
-
@State private var isButtonDisabled = true
defines a Boolean@State
variable calledisButtonDisabled
and set its initial value to true. The@State
attribute tells SwiftUI to monitor this variable for changes and rerender the views when it changes. -
Button("Tap me") { print("Button tapped") } .disabled(isButtonDisabled)
creates aButton
view and sets its disabled state based on theisButtonDisabled
variable. Initially, sinceisButtonDisabled
is true, the button is disabled. -
Button("\(isButtonDisabled ? "Enable" : "Disable") me") { isButtonDisabled = false }
is anotherButton
view. When this button is tapped, it toggles theisButtonDisabled
state, switching whether the first button is disabled. -
VStack
Both buttons are placed inside a VStack view, which arranges its child views in a vertical line
Disabling a button in SwiftUI is a crucial aspect of creating a user-friendly and accessible interface. By dynamically managing the disabled state of buttons based on certain conditions, you can improve the user experience and prevent the execution of unpermitted actions.