SwiftUI: Top items dissappear when have infinite LazyVGrid ScrollView on M1 iPad Pro

77 views Asked by At

Edit: This problem seems disappeared after iOS 17.2

I implemented an infinite scroll view using LazyVGrid and ScrollView, but if I scroll far enough (like the number reaches 1500+ in the below minimal example), if I tap top and go back, the first few items in the list will just disappear. If try scroll up now, the app will crash.

Strange thing is, this seems only happen on my M1 iPad Pro physical device, not on iPhone 15 Pro or any simulators in Xcode. Anyone may have any idea why it could happen? Thanks.

Minimal Code:

ContentView.swift

import SwiftUI

struct ContentView: View {
    @State var titles = [String]()
    
    let columns = [
        GridItem(.adaptive(minimum: 160), spacing: 20, alignment: .top)
    ]
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(titles, id: \.self) { title in
                    ChildView(title: title)
                        .onAppear {
                            if title == titles.last {
                                let randomInt = Int.random(in: 0..<100)
                                let result = (titles.count...titles.count+randomInt)
                                    .map { value in
                                        String(value)
                                    }
                                titles.append(contentsOf: result)
                            }
                        }
                }
            }
        }
        .onAppear {
            let randomInt = Int.random(in: 0..<100)
            let result = (titles.count...titles.count+randomInt)
                .map { value in
                    String(value)
                }
            titles.append(contentsOf: result)
        }
    }
}

ChildView.swift

import SwiftUI

struct ChildView: View {
    let title: String
    var body: some View {
        Text(title)
            .frame(height: 100)
    }
}
0

There are 0 answers