Search code examples
swiftswiftuiswiftui-tabviewswiftui-foreach

How to update SwiftUI's ForEach in a TabView with PageTabViewStyle modifier when inserting a new element to the collection at first index


This is a very specific issue when using ForEach in a TabView with PageTabViewStyle modifier.

Every time I'm inserting an element at the beginning of my array my app crashes.

I'm getting a

attempt to delete item 11 from section 0 which only contains 11 items before the update

error.

In the canvas it crashes too.

Regular appending at the end works fine, also when I remove the PageTabViewStyle modifier it works.

Let me know if I need to elaborate more or if there are questions.

Update: I seems in iOS 15 this issue has been fixed and my code works. I'm still hoping to find a iOS 14 workaround.

I've reproduced the issue with a simple one page app:

import SwiftUI

struct SwiftUIView: View {

    @State var myArray: [String] = ["C", "D", "E", "F", "G"]

    var body: some View {

        VStack {
            Button("Insert before", action: {
                myArray.insert("A", at: 0)
            })
            TabView {
                ForEach(myArray, id: \.self) { value in
                    Text("\(value)")
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

Solution

  • Here is tested workaround for Xcode 12.5 / iOS 14.5.

    TabView {
        ForEach(myArray, id: \.self) { value in
            Text("\(value)")
        }
    }
    .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    .id(myArray.count)      // << here !!