0

I need to pass the focus from one TextField to another textfield when user clicks on continue button of keyboard. Now i want a generic textfield which i can be used everywhere in the app so i created a reusable component

struct MyTextField: View {
    
    @Binding var text: String

 TextField("", text: $text)
                .font(Font.custom(Constants.INTER_MEDIUM, size: 16))
                .keyboardType(keyboardType)
                .foregroundColor(Constants.GRAY_COLOR)
                .submitLabel(submitLabel)
                //.focused() Issue is over here , how to make it more generic

}

Now how do i pass the focused property to the TextField to make it more generic and reusable. I was looking through this answer but the issue is using the enum Field does not make it reusable across the project.

Go Fudge YourSelves
  • 139
  • 1
  • 2
  • 10
  • What will you gain from this, you would at least have to declare the focus variable as a binding property and as a state property everywhere you use the struct. Probably better to use .focused as a modifier to your struct than to encapsulate it – Joakim Danielson Sep 15 '22 at 07:45

1 Answers1

1

I'm not sure how to make it generic, but I don't think it's necessary. Just annotate your custom textfield with the designated focused state. Yes, you might have to use different enums in different views, but it should work fine with your custom struct.

enum MySelectedField { 
    case first, second, third
}

struct MyTextField: View {
    @Binding var text: String

    // your custom TextField implementation WITHOUT .focused
}

struct MyTextFieldList: View {
    @FocusState private var selectedField: MySelectedField?
    @State var firstText = ""
    @State var secondText = ""
    @State var thirdText = ""

    var body: some View {
        VStack {
            MyTextField(text: $firstText)
                .focused($selectedField, equals: .first)
            MyTextField(text: $secondText)
                .focused($selectedField, equals: .second)
            MyTextField(text: $thirdText) 
                .focused($selectedField, equals: .third)
        }
    }
}
Nobadi
  • 121
  • 2
  • 13