SwiftUI,如何将值传递给工作表上显示的视图?

问题描述 投票:0回答:1

我正在尝试将一个值传递给工作表上显示的子视图。初始值设置为“Fred”。单击按钮时,值将更改为“Jane”,然后显示工作表。哎呀!当工作表出现时,值仍然是“Fred”。我做错了什么?


struct ContentView: View {
    @State private var firstName = "Fred"
    @State private var presentSheet = false
    var body: some View {
        Button {
            firstName = "Jane"
            presentSheet.toggle()
        } label: {
            Text("go to sheet")
        }
        .sheet(isPresented: $presentSheet) {
            SubView(theName: firstName)
                .presentationDetents([.medium])
        }
    }
}

struct SubView: View {
    let theName: String
    var body: some View {
        Text("theName = \(theName)")
    }
}
swiftui parameter-passing
1个回答
0
投票

尝试将

theName
设置为
@Binding
值。不然不会更新

@Binding var theName: String
© www.soinside.com 2019 - 2024. All rights reserved.