如何在自定义结构或类中的SwiftUI中订阅状态属性更改

时间:2019-11-20 14:05:54

标签: uikit swiftui

刚开始使用SwiftUI时,就意识到由于某种原因,UIKit中有很多组件必须包装在UIViewControllerRepresentable中才能在SwiftUI代码中使用。其中之一应对@ State / @ Binding参数的更改做出反应,该参数在单独的组件中已更改。问题是我需要以某种方式订阅该状态参数并在包装结构中处理其更新。但是我找不到任何允许这样做的Binding <>道具。

有一个简单的例子

struct SwiftUIView: View {
    @State private var state:Bool = false
    var body: some View {
        Foo(state: self.$state)
    }
}

struct Foo<Content: View>: UIViewControllerRepresentable {
    var state: Binding<Bool>
    init(state: Binding<Bool>) {
        self.state = state
        // how to watch this param and handle every change by calling bar function?
    }

    func bar(newState: Bool) {
        print(newState)
    }
    func makeUIViewController() {}
    func updateUIViewController() {}
}

也许应该有另一种方法?

1 个答案:

答案 0 :(得分:0)

我向您展示了一个可行的示例。您可以像这样获得自然更新的绑定值。

 struct SwiftUIView: View {
@State private var state:Bool = false
var body: some View {
    Group{
    Button(action: {
        self.state.toggle()
    }, label: {Text("Text Button")})
        Foo(state: self.$state)
    }
}
}

struct Foo: UIViewRepresentable {



var state: Binding<Bool>


func bar(newState: Bool) {
    print(newState)
}

func makeUIView(context: UIViewRepresentableContext<Foo>) -> UIView {
let vc = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
  vc.backgroundColor = UIColor.red
  return vc
}

func updateUIView(_ uiViewController: UIView, context: UIViewRepresentableContext<Foo>) {
    bar(newState: self.state.wrappedValue)
}
}