简体   繁体   中英

How to make SwiftUi textfield more genric for focus state?

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.

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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM