SwiftUI TextField: OnSubmit Label


SwiftUI 3 introduced the ability to change return key label text to some of the predefined values with a modifier called submitLabel; it’s an enum with the values of join, return, continue, done, go, next, route, search and send.

We will add labels for email and confirm the email field. Return key label for the email will be called “next” and “done” for the confirm email TextField.
struct TextFieldExample: View {
    
    @State private var email = ""
    @State private var confirmEmail = ""
    @State private var borderColor: Color = .gray
    
    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))
HStack {
                Image(systemName: "person.crop.circle.fill")
                    .foregroundColor(.gray).font(.headline)
                TextField("Email", text: $email)
                    .keyboardType(.emailAddress)
                    .submitLabel(.next)
            }
            .padding()
            .overlay(RoundedRectangle(cornerRadius: 8).stroke(borderColor, lineWidth: 1))
            .padding(.horizontal)
        
            HStack {
                Image(systemName: "person.crop.circle.badge.checkmark")
                    .foregroundColor(.gray).font(.headline)
                TextField("Confirm email", text: $confirmEmail)
                    .keyboardType(.emailAddress)
                    .disabled(email.isEmpty)
                    .onSubmit {
                        validateEmail()
                    }
                    .submitLabel(.done)
            }
            .padding()
            .overlay(RoundedRectangle(cornerRadius: 8).stroke(borderColor, lineWidth: 1))
            .padding(.horizontal)
        }
    }
    
    private func validateEmail() {
        if email.localizedCaseInsensitiveCompare(confirmEmail) == .orderedSame {
            borderColor = .green
        } else {
            borderColor = .red
        }
    }
}




Our return key label reads “next” but it dismisses the keyboard upon tapping instead of going to the next TextField. This is where SwiftUI 3’s new modifier .focused and newly introduced property wrapper @FocusStatecan help us.