Disable and Enable a Button in SwiftUI
This tutorial will teach us how to disable or enable a button or any other view in SwiftUI. It is pretty easy to achieve this functionality in SwiftUI with the help of a disabled modifier of SwiftUI.
We mostly disable any view based on some conditions and then enable it when the required conditions are met.
What we’ll cover in this blog
- How to disable/enable a button.
- Disabled modifier.
- onChange modifier.
Let’s see how we disable a button in SwiftUI.
struct ContentView:View{ @State var isEmailGiven=false @State var email = "" var body: some View{ VStack{ TextField("Enter Email", text: $email) .textFieldStyle(.roundedBorder) .padding(.horizontal,20) .padding(.bottom, 30) Button("Create Account") { //Do something here } .disabled(email.isEmpty) }.tint(Color.teal) } }
Here in this example, we have taken a TextField and bound it with a State variable email. So that view will update whenever the text inside the email changes.
There is a button that we have currently disabled by using the disabled modifier and we have given it the isEmpty property of the state variable email.
The button will be enabled as soon as we enter the text inside Textfield.
When a user enters his email ID, the Create Account button will be enabled and the user will be able to create an account.
onChange method in SwiftUI to enable and disable a button
The same thing in SwiftUI can be achieved with the onChange method of TextField. And in the onChange method, we can write some more complex conditions.
We can write conditions for validating our email address like whether it’s a valid email address or not and disable and enable the button based on these conditions.
Let’s see how we can use onChange method for enabling and disabling the Button.
//Disable and Enable a Button in SwiftUI struct ContentView:View{ @State var isEmailGiven=false @State var email = "" var body: some View{ VStack{ TextField("Enter Email", text: $email) .onChange(of: email) { newValue in if !self.email.isEmpty{ self.isEmailGiven = true r } self.isEmailGiven = false } .textFieldStyle(.roundedBorder) .padding(.horizontal,20) .padding(.bottom, 30) Button("Create Account") { //Do Create account } .disabled(!isEmailGiven) // for disabling button }.tint(Color.teal) } }
And as the name depicts, the onChange method will be called whenever Textfield’s text changes.
Leave a Reply