应用`listRowInsets`时SwiftUI列表未更新 [英] SwiftUI List not getting updated when `listRowInsets` are applied

查看:51
本文介绍了应用`listRowInsets`时SwiftUI列表未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击更新List中的数据

.listRowInsets 应用于列表行时,列表在状态改变时停止获取更新.

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

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?

推荐答案

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

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

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

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:) 应该只用于常量 数据.而是使数据符合 Identifiable 或使用 ForEach(_:id:content:)并提供一个明确的id

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

这篇关于应用`listRowInsets`时SwiftUI列表未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆