51 - Disable a Button in SwiftUI

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.

This code does the following:

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.