TextField works well with SwiftUI’s .disabled modifier.
Let’s say we want users to confirm their email address but we only want to enable confirm email TextField when the user has entered a value in email TextField, for this use case, we can use disabled modifier as shown below.
struct TextFieldExample: View {
@State private var email = ""
@State private var confirmEmail = ""
var body: some View {
VStack {
Image("dt")
.resizable()
.frame(width: 100, height: 100)
.clipShape(Circle())
.shadow(color: Color.black, radius: 2, x: 1, y: 1)
.overlay(Circle().stroke(Color.gray, lineWidth: 2))
//username
HStack {
Image(systemName: "person.crop.circle.fill")
.foregroundColor(.gray).font(.headline)
TextField("Email", text: $email)
.keyboardType(.emailAddress)
}
.padding()
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.gray, lineWidth: 1))
.padding(.horizontal)
// password
HStack {
Image(systemName: "person.crop.circle.badge.checkmark")
.foregroundColor(.gray).font(.headline)
TextField("Confirm email", text: $confirmEmail)
.keyboardType(.emailAddress)
.disabled(email.isEmpty)
}
.padding()
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.gray, lineWidth: 1))
.padding(.horizontal)
}
}
}