1

I have two TextFields that use onCommit. Pressing enter saves the value. However, this does not automatically move the cursor to the next TextField. I want it to work like the tab button which moves the cursor to next TextField but this doesn't save the value (due to onCommit requiring enter/return to be pressed). The best solution I have found is using a button but that results in poor usability as I would be using a ForLoop over this view.

struct ModuleDetailView: View {
    @Binding var subjectDetails: [Subjects]
    @State private var subject = ""
    @State private var grade = ""
    var body: some View {
        VStack {
            TextField("Subject", text: $subject, onCommit: appendData)
            TextField("Grade", text: $grade, onCommit: appendData)
            VStack {
                Text("Output")
                ForEach(subjectDetails) { subject in
                    HStack {
                        Text(subject.name)
                        Text(subject.grade)
                    }
                }
            }
        }
    }
    
    func appendData() {
        if subject != "" && grade != "" {
            let module = Subjects(name: subject, grade: grade)
            subjectDetails.append(module)
        }
    }
}

The preview code:

struct ModuleDetailView_Previews: PreviewProvider {
    static var previews: some View {
        PreviewWrapper()
    }
    struct PreviewWrapper: View {
        @State var modules = [Subjects]()
        var body: some View {
            ModuleDetailView(subjectDetails: $modules)
        }
    }
}

both textfields are visible at the same time. What happens is that after I press enter from the first textField the cursor just vanishes, which works differently from when we press TAB - simply moves to the next. And I want it to work similar to how it behaves when TAB is pressed. Therefore, in this case using a firstResponder might not be a good option

Subjects struct:

struct Subjects: Identifiable {
    let id = UUID()
    var name: String
    var grade: String
}
NotAPhoenix
  • 171
  • 4
  • 15
  • Does this answer your question? [SwiftUI: How to make TextField become first responder?](https://stackoverflow.com/questions/56507839/swiftui-how-to-make-textfield-become-first-responder) – lorem ipsum Feb 09 '21 at 13:13
  • I am afraid not, as both textfields are visible at the same time. What happens is that after I press enter from the first textField the cursor just vanishes, which works differently from when we press TAB - simply moves to the next – NotAPhoenix Feb 09 '21 at 14:07

0 Answers0