我希望根据数组的索引设置ForEach视图的动画,以下是我的代码:
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
}
}
当我面对一个小尺寸的数组时,这种方法似乎工作得很好,我使用这种方法的问题是,我必须应用一次更新索引逻辑,然后在它之后对数组进行排序.我认为这是一种好的方法,但还很遥远.我想知道是否有更简单的方法或方法可以更好地处理大型array.这个问题的目的是寻找一种在性能上更好的方法.