SwiftUI List not getting updated when `listRowInsets` are applied

大憨熊 提交于 2020-12-13 04:32:01

问题


Goal

Update data in a List on tap

Problem

When .listRowInsets are applied to the list rows, the list stops getting updates when the state changes.

Code

struct ContentView: View {
    
    private var array = ["a", "b", "c"]
    @State private var selectedIndex = 0
    
    var body: some View {
        makeBody()
    }
    
    private func makeRow(_ t: String, index: Int) -> some View {
        return HStack {
            Text(t)
            Spacer()
            if selectedIndex == index {
                Image(systemName: "checkmark.circle")
            }
        }
        .contentShape(Rectangle())
        .onTapGesture {
            print("selected \(index)")
            self.selectedIndex = index
        }
    }
    
    private func makeBody() -> some View {
        return List {
            ForEach(0..<array.count) { i in
                self.makeRow(self.array[i], index: i)
                    // comment and uncomment this line
                    // .listRowInsets(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20))
            }
        }
    }
}

Question

Is this a bug? Or am I missing something?


回答1:


If your data can be changed, you need a dynamic ForEach loop (with an explicit id parameter):

ForEach(0..<array.count, id:\.self) { i in // <- add `id:\.self`
    self.makeRow(self.array[i], index: i)
         .listRowInsets(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20))
}

It's not well documented though. In some cases Xcode warns you when you try to modify your array used in a ForEach loop:

ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!



来源:https://stackoverflow.com/questions/62666863/swiftui-list-not-getting-updated-when-listrowinsets-are-applied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!