我想根据数组的索引为我的 ForEach View 设置动画,这是我的代码:
struct ContentView: View {
@State private var array: [MyType] = [MyType("A"), MyType("B"), MyType("C"), MyType("D")]
var body: some View {
VStack(spacing: 10.0) {
ForEach(array, id:\.id) { item in
Text(item.string)
.frame(width: 25, height: 25)
.background(Color.gray.opacity(0.5).cornerRadius(5.0))
}
.animation(.default, value: array)
Button("Move to down") {
array.indices.forEach { index in
if ((array[index].index + 1) < array.count) { array[index].index += 1 }
else { array[index].index = 0 }
}
array.sort(by: { (lhs, rhs) in return (lhs.index < rhs.index) })
}
}
.fixedSize()
.padding()
}
}
struct MyType: Equatable {
private static var nextIndexValue: Int = 0
let id: UUID = UUID()
var index: Int
var string: String
init(_ string: String) {
self.index = MyType.nextIndexValue
self.string = string
MyType.nextIndexValue += 1
}
}
当我面对小尺寸数组时,这种方法似乎工作得很好,这种方法的问题是我必须应用一次更新索引逻辑,然后立即对数组进行排序。我认为这距离成为一个好的方法还很遥远。我想知道是否有一种更简单的方法或方法可以更好地处理大型数组。这个问题的目标是寻找一种性能更好的方法。
最佳答案
不太确定你的意思,但 next 以更简单的方式执行相同的操作,并且根本不依赖于索引:
Button("Move to down") {
let last = array.removeLast()
array.insert(last, at: 0)
}
关于swift - 在 SwiftUI 中的 ForEach 中使用 id 时,如何对数组的索引进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73379119/