Home > Enterprise >  How can I animated index of an array when using an id in ForEach in SwiftUI
How can I animated index of an array when using an id in ForEach in SwiftUI

Time:08-17

I want animate my ForEach view depending the index of array, here is my code:

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
    }
    
}

This approach seems works fine when I am facing with a small size array, my issue with this approach is that I have to apply my updating index logic once and then sorting the array right after it. Which I believe it is far away to be a good approach. I was wondering if there is a simpler way or approach that could be better approach with large arrays. The goal of this question is searching for an approach that is better in performance.

CodePudding user response:

Not really sure what do you mean, but next does the same in much simpler way and does not depend on indices at all:

Button("Move to down") {
    let last = array.removeLast()
    array.insert(last, at: 0)
}
  • Related