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 = truedefines a Boolean@Statevariable calledisButtonDisabledand set its initial value to true. The@Stateattribute tells SwiftUI to monitor this variable for changes and rerender the views when it changes.
- 
Button("Tap me") { print("Button tapped") } .disabled(isButtonDisabled)creates aButtonview and sets its disabled state based on theisButtonDisabledvariable. Initially, sinceisButtonDisabledis true, the button is disabled.
- 
Button("\(isButtonDisabled ? "Enable" : "Disable") me") { isButtonDisabled = false }is anotherButtonview. When this button is tapped, it toggles theisButtonDisabledstate, switching whether the first button is disabled.
- 
VStackBoth 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.