为什么@State值未更新

安卓

我有三个按钮,每个按钮对应一个数据数组中的值。当用户单击按钮时,相应的值将显示在工作表窗口中。这是我的代码:

struct TestView: View {
    @State var data: [Int] = [100, 200, 300]
    @State var presented: Bool = false
    @State var index4edit: Int = 1
    
    var body: some View {
        HStack{
            ForEach(1..<4){ index in
                Button(action: {
                    index4edit = index
                    presented.toggle()
                }){ Text(String(index)) }
                .frame(width: 30, height: 30)
                .padding()
            }
        }
        .sheet(isPresented: $presented, content: {
            Text("\(index4edit): \(data[index4edit-1])")
        })
    }
}

我的问题是,第一次单击按钮时,无论哪个按钮,它总是显示第一个数据100原因是数据index4edit没有在第一次单击时更新1,而是始终更新,但为什么呢?谢谢。

达维杰夫

这是因为工作表视图是基于“视图初始化”创建的。更改状态时,将不会重新创建视图,因为视图中未使用State变量。

要解决此问题,只需在代码中的某个地方使用您的State变量,例如此虚拟示例

HStack{
    ForEach(1..<4){ index in
        Button(action: {
            index4edit = index
            presented.toggle()
        }){ Text(String(index) + (index4edit == 0 ? "" : "")) } //<<here is the State used
        .frame(width: 30, height: 30)
        .padding()
    }
}

现在,当状态更改时,您的视图将重新呈现,因此工作表视图将被重新呈现。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章