Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

SwiftUI provides a modifier to disable/enable buttons.
SwiftUI provides a modifier to disable/enable buttons.

This code does the following:

  • @State private var isButtonDisabled = true defines a Boolean @State variable called isButtonDisabled 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 a Button view and sets its disabled state based on the isButtonDisabled variable. Initially, since isButtonDisabled is true, the button is disabled.

  • Button("\(isButtonDisabled ? "Enable" : "Disable") me") { isButtonDisabled = false } is another Button view. When this button is tapped, it toggles the isButtonDisabled 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.