swiftui - ForEach 具有动态与静态范围
问题描述
我敢肯定,我一直在努力解决另一个简单的问题。我似乎找不到在动态范围内使用 ForEach 的正确方法。
我有以下简单的演示来显示我的问题。anySquare 上的 tapGesture 将更新 @State 变量数组以使正方形 1 消失/出现。像右侧的魅力一样工作,但不在 ForEach 内。
@State var visibilityArray = [true,true]
var body: some View {
ZStack {
Color.white
HStack {
VStack{
Text("Dynamic")
ForEach(visibilityArray.indices) { i in
if self.visibilityArray[i] {
Rectangle()
.frame(width: 100, height: 100)
.overlay(Text(String(i)).foregroundColor(Color.white))
.onTapGesture {
withAnimation(Animation.spring()) {
self.visibilityArray[1].toggle()
}
}
}
}
}
VStack{
Text("Static")
if self.visibilityArray[0] {
Rectangle()
.frame(width: 100, height: 100)
.overlay(Text("0").foregroundColor(Color.white))
.onTapGesture {
withAnimation(Animation.spring()) {
self.visibilityArray[1].toggle()
}
}
}
if self.visibilityArray[1] {
Rectangle()
.frame(width: 100, height: 100)
.overlay(Text("1").foregroundColor(Color.white))
.onTapGesture {
withAnimation(Animation.spring()) {
self.visibilityArray[1].toggle()
}
}
}
}
}
}
}
解决方案
当您尝试修改ForEach
循环中使用的数组(例如,通过将其替换为另一个数组)时发生的 Xcode 错误提供了一个很好的指导:
ForEach(_:content:)
应该只用于常量数据。而是使数据符合Identifiable
或使用ForEach(_:id:content:)
并提供明确的id
!
您可以使用此代码来完成您的ForEach
工作:
ForEach(visibilityArray, id: \.self) {
这也意味着对于循环中的每个项目,您必须返回一些View
. 我建议将过滤后的数组(仅包含您想要显示/使用的项目)作为ForEach
循环的输入。
推荐阅读
- sql - SQL 查询以计算是否由 2 行限制的多行与 bool 标志为 true 满足特定条件
- bash - 循环遍历日期的bash脚本卡住了?
- python - 请让我知道如何将 GEKKO 参数放入变量中
- python - 在熊猫数据框中就地替换值不适用于 .replace()
- c - 睡眠()导致管道破裂?
- python - Beautiful Soup 4 没有拉下此网页上的所有 html
- java - Android SpeechRecognizer如何使连续?
- java - 使用方法填充二维数组时如何修复数组错误和 ArrayStoreException
- python - 如何使我的第二个循环中的数据保存在 csv 的另一行中
- json - 从Angular中的Json文件中按特定字段获取数据