小编ree*_*der的帖子

SwiftUI 显示带有绑定变量的工作表在首次显示时不起作用

我试图在工作表中呈现一个带有 @Binding String 变量的视图,该变量仅在 TextField 中显示/绑定该变量。

在我的主 ContentView 中,我有一个字符串数组,我用 ForEach 循环显示该数组的索引,显示一个按钮,每个按钮都包含循环元素的文本。

按钮操作很简单:将 @State“索引”变量设置为按下的按钮的元素索引并显示工作表。

这是我的内容视图:

struct ContentView: View {
    
    @State var array = ["first", "second", "third"]
    @State var showIndex = 0
    @State var showSheet = false
    
    var body: some View {
        VStack {
            ForEach (0 ..< array.count, id:\.self) { i in
                Button("\(array[i])") {
                    showIndex = i
                    showSheet = true
                }
            }
            // Text("\(showIndex)") // if I uncomment this line, it works!
        }
        .sheet(isPresented: $showSheet, content: {
            SheetView(text: $array[showIndex])
        })
        .padding()
    } …
Run Code Online (Sandbox Code Playgroud)

macos binding state swiftui

8
推荐指数
2
解决办法
2274
查看次数

标签 统计

binding ×1

macos ×1

state ×1

swiftui ×1