1

I trying to display a dynamic page tab view but it keep crash without the error code. The crashed happened when the number of tab view decrease. I cant find what's wrong with my code. So I tested in the sample project but it still the same. In the sample project when I clicked 3 and then clicked other numbers will got no problem, but when I clicked again 3 and scroll the tab view, it will crashed. Here is my sample project.

struct ContentView: View {
    @ObservedObject var dataClass = DataClass()
    var body: some View {
        VStack(){
            List{
                ForEach(3..<6){ i in
                    Text("\(i)")
                        .onTapGesture {
                            self.dataClass.load(num: i)
                        }
                }
            }
            if dataClass.data.count != 0{
                TabView{
                    ForEach(dataClass.data.indices, id: \.self){ i in
                        Text(dataClass.data[i].alp)
                    }
                }.tabViewStyle(PageTabViewStyle())
                .padding(.horizontal)
                .background(Color.red)
            }
        }
    }
}

class DataClass : ObservableObject {
    @Published var data : [DataStruct] = [DataStruct]()
    
    init() {
        
    }
    func load(num : Int){
        if num == 3 {
            data = [DataStruct(num: 1, alp: "a"), DataStruct(num: 2, alp: "b"), DataStruct(num: 3, alp: "c")]
        }
        if num == 4 {
            data = [DataStruct(num: 4, alp: "d"), DataStruct(num: 5, alp: "e"), DataStruct(num: 6, alp: "f"), DataStruct(num: 7, alp: "g")]
        }
        if num == 5 {
            data = [DataStruct(num: 8, alp: "h"), DataStruct(num: 9, alp: "i"), DataStruct(num: 10, alp: "j"), DataStruct(num: 11, alp: "k")]
        }
    }
}
struct DataStruct {
    var num : Int
    var alp : String
}
Aatrox11
  • 65
  • 4

0 Answers0