【问题标题】:SwiftUI List not getting updated when `listRowInsets` are applied应用`listRowInsets`时SwiftUI列表未更新
【发布时间】:2020-06-30 22:09:44
【问题描述】:

目标

随时更新List 中的数据

问题

.listRowInsets 应用于列表行时,列表会在状态更改时停止更新。

代码

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))
            }
        }
    }
}

问题

这是一个错误吗?还是我错过了什么?

【问题讨论】:

    标签: swiftui-list swiftui


    【解决方案1】:

    如果您的数据可以更改,您需要一个动态的ForEach 循环(带有显式id 参数):

    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))
    }
    

    虽然没有很好的记录。在某些情况下,当您尝试修改 ForEach 循环中使用的数组时,Xcode 会警告您:

    ForEach(_:content:) 只能用于常量数据。 而是将数据符合Identifiable 或使用ForEach(_:id:content:) 并提供明确的id!

    【讨论】:

    • 行得通!你有那个来源吗?我找不到任何关于id 参数和动态ForEach...
    • @youjin 没错,我在 Apple 文档中找不到任何明确的内容。也许我错过了什么。无论如何,我添加了一个 Xcode 警告,它提供了一个很好的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多