【问题标题】:SwiftUI @Binding MisunderstandingSwiftUI @Binding 误解
【发布时间】:2020-07-25 17:09:10
【问题描述】:

我正在尝试使用 @Binding 更新父视图中的值。我的代码没有按预期工作。

struct Trade: View {
    @Binding var showSheet: Bool
    @Binding var bool: Bool
    
    var body: some View {
        Button("Trade") {
            self.showSheet = true
            self.bool = false
        }
            .font(.title)
            .foregroundColor(.white)
    }
}

struct Profile: View {
    @State var showSheet: Bool = false
    @State var bool: Bool = false
    
    var body: some View {
        VStack {
            Trade(showSheet: $showSheet, bool: $bool)
                .sheet(isPresented:  $showSheet) {
                    Text("HELLO, WORLD.")
            }
        }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(bool ? Color.green : Color.red)
            .edgesIgnoringSafeArea(.all)
    }
}

如我所料,showSheet @State 正在更新。点击时,传递给 Button 初始化程序的闭包将显示工作表,但 @bool 永远不会更新。我是不是误会了什么?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    这是因为您没有更新它(即,它使用false 并在按钮操作中分配false - 没有更改!)

    Button("Trade") {
        self.showSheet = true
        self.bool = true      // << fix !!
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2019-11-03
      • 2019-12-11
      • 2019-11-29
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2020-03-22
      • 2021-03-31
      相关资源
      最近更新 更多