foreach循环中的快速变量和枚举

发布于 2025-02-12 05:51:49 字数 815 浏览 0 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2025-02-19 05:51:49

对于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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文