簡體   English   中英

在列表頂部插入項目時如何在 LazyVStack / VStack 中保持滾動 position

[英]How to maintain scroll position in LazyVStack / VStack when insert item at the top of a list

我創建了一個簡單的垂直列表,其中包含要顯示的項目。

問題是當我通過insertAtTop()在列表頂部插入項目時。 滾動視圖不會停留在同一個地方。

觀看視頻: https://streamable.com/i7ywab


如何使滾動視圖保持在同一個 position 中?

這是示例代碼。

struct TestView: View {
    
    @State private var items: [Item] = []
    
    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    ForEach(items, id: \._id) { item in
                        Text(item.text)
                            .background(Color.green)
                            .padding(.bottom, 10)
                    }
                }
            }
            .navigationBarItems(trailing: HStack {
                Button("[Insert at top]", action: {
                    insertAtTop()
                })
                Spacer(minLength: 20)
                Button("[Load]", action: {
                    load()
                })
            })
            .navigationTitle("Item List")
        }
    }
    
    private func load() {
        items = (1...50).map { _ in Item() }
    }
    
    private func insertAtTop() {
        let newItems = (1...20).map { _ in Item() }
        items.insert(contentsOf: newItems, at: 0)
    }
    
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

struct Item {
    var _id = UUID()
    var text = UUID().uuidString.prefix(5)
}

只有在列表頂部添加視圖時,才會出現問題。 如果您修改替換現有視圖,則沒有問題。

...因此一種解決方法是將您的 ForEach 循環到一個占位符數組上,該數組在負方向上具有大量視圖(例如 10000)。 然后在您的 ForEach 中,檢查索引以查看它是否存在於真實/非占位符數組中。

如果是 -> 真實視圖 如果不是 -> 廉價視圖(例如,具有正確背景顏色和高度為 1 的 Rectangle())。

    LazyVStack {
ForEach(placeholderIndices, id: \.self) { index in
    if indices.contains(index) {
    
    REAL VIEW
    
    } else {
    
    Rectangle()
    .fill(Color.bg)
    .frame(height: 0)
    
    }
    }

當您展開視圖時,placeholderIndices 保持不變; 只有“真正的”指數會改變

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM