简体   繁体   English

如何使 SwiftUi 文本字段更适合焦点 state?

[英]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.当用户单击键盘的继续按钮时,我需要将焦点从一个TextField字段传递到另一个textfield Now i want a generic textfield which i can be used everywhere in the app so i created a reusable component现在我想要一个通用的textfield ,我可以在应用程序的任何地方使用它,所以我创建了一个可重用的组件

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.现在我如何将焦点属性传递给 TextField 以使其更通用和可重用。 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.只需使用指定的焦点 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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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