swift - 在 SwiftUI 中的 ForEach 中使用 id 时,如何对数组的索引进行动画处理

标签 swift swiftui

我想根据数组的索引为我的 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/

相关文章:

ios - 如何设置 UIHostingController 背景颜色清除?

Swift:每次单击按钮时显示一个随机数组索引

ios - 使用 UIPageControl 构建文本轮播的正确方法

ios - swift ·哈内克 : Json Data in TextView

ios - SwiftUI - 此代码是否实例化一个新的场景对象?

swift - 更改在特定边上带有边框的功能以也能够适应拐角半径?

ios - 在 MacCatalyst 的 SwiftUI 应用程序中隐藏标题栏

swift - UIButton的方法 "backgroundRect(forBounds:)"是做什么用的?

ios - 如何更改导航 Controller 后退按钮的字体大小

SwiftUI @FetchRequest 使应用程序崩溃并返回错误