迅速-状态的ForEach循环 [英] swift - ForEach loop with state

查看:62
本文介绍了迅速-状态的ForEach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有此代码:

@State var n = 3
var body: some View {
    VStack {
        Button(action:{
            if self.n == 3 {
                self.n = 5
            } else {
                self.n = 3
            }
        }) {
            Text("Click me")
        }
        ForEach(1..<self.n+1) { i in
            Text(String(i))
        }
    }
}

我希望该代码在 1 2 3 1 2 之间切换>单击按钮时,屏幕上的 3 4 5 ,但是它仅显示 1 2 3 .我该如何解决?

I expect this code to toggle between 1 2 3 and 1 2 3 4 5 on the screen when you click the button, however it only shows 1 2 3. How would I fix this?

推荐答案

如果项目数恒定,则使用的 ForEach 形式可以,但是如果View可能会更改,则您需要提供符合协议 Identifiable 的项目,或使用提供 id::

The form of ForEach that you have used is fine if the number of items is constant, but if the Views might change, then you need to either provide items that conform to the protocol Identifiable, or use the form of ForEach that provides the id::

ForEach(1..<self.n+1, id: \.self) { i in
    Text(String(i))
}

作为 id 传递的值是一个 KeyPath ,它告诉SwiftUI项目的哪个属性用作其标识符.对于 Int ,您可以使用 Int 的值,该值可以通过 .self 属性进行访问.

The value passed as id is a KeyPath that tells SwiftUI which property of the item to use as its identifier. In the case of an Int, you can just use the Int's value which can be accessed through the .self property.

SwiftUI使用标识符来了解何时添加或删除了 ForEach 中的项目,因此需要它们才能使您看到更改.

SwiftUI uses the identifiers to know when items in the ForEach have been added or removed, thus it needs them for you to be able to see the change.

这篇关于迅速-状态的ForEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆