foreach循环中的快速变量和枚举
我有一个foreach循环,根据用户条目,我一遍又一遍地显示X字段(即它们输入5,它显示这些字段的5次迭代)。
我需要能够动态为这些字段设置TextField,Focusistate和可访问性的FocusState绑定。我知道我必须将枚举符合为案例词,但我不能单独定义无限数量的枚举案例,以防用户输入我配置枚举案例之外的值之外的值。
我还意识到,在我的示例中,我只定义了一个@State变量,但是由于问题,您如何在执行此类操作时如何定义X变量?
这是一个例子:
struct TestView: View {
@AccessibilityFocusState var accessFocus: AccessFocusField?
@FocusState var isFocused: Field?
@State private var field = ""
enum AccessFocusField: CaseIterable {
case fieldName
}
enum Field: CaseIterable {
case fieldName
}
var body: some View {
ForEach(1...5) { value in
TextField("Hello World!", $field[value])
.focused($isFocused, equals: .fieldName[value]
.accessibilityFocused($accessFocus, equals: .fieldName[value])
}
}
}
I have a ForEach loop in which I am displaying X amount of fields over and over again depending on user entry (i.e. they enter 5, it displays 5 iterations of these fields).
I need to be able to set the TextField, FocusState, and AccessibilityFocusState bindings for these fields dynamically. I know I have to conform the enum to CaseIterable but I can't separately define an infinite number of enum cases just in case a user enters a value outside of that in which I have configured enum cases.
I also realize that in my example I have only defined a single @State variable, but as this goes along with the question, how do you define X amount of variables when doing something like this?
Here's an example:
struct TestView: View {
@AccessibilityFocusState var accessFocus: AccessFocusField?
@FocusState var isFocused: Field?
@State private var field = ""
enum AccessFocusField: CaseIterable {
case fieldName
}
enum Field: CaseIterable {
case fieldName
}
var body: some View {
ForEach(1...5) { value in
TextField("Hello World!", $field[value])
.focused($isFocused, equals: .fieldName[value]
.accessibilityFocused($accessFocus, equals: .fieldName[value])
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于foreach,我将创建一个可识别的对象,命名字段具有Textfield所需的所有属性。然后声明该对象的数组,然后在foreach中使用它。
For ForEach I would create an identifiable object, named Field with all the properties that Textfield needs. And then declare an array of that object, and use that in ForEach.