【问题标题】:How to subscribe to state property change in SwiftUI in custom struct or class如何在自定义结构或类中订阅 SwiftUI 中的状态属性更改
【发布时间】:2019-11-20 14:05:54
【问题描述】:

刚开始使用 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() {}
}

也许应该有另一种方法?

【问题讨论】:

  • 嗯,我认为您真正想要完成的工作需要更多细节。一种方法是使 Foo 成为 ObservableObject 并在那里声明状态,然后在 View 中使用它。您可以在可观察对象的状态上使用 didSet 块并调用该函数。
  • 好的,想象一下 Foo 结构实现了 UIViewControllerRepresentable 并为 UIScrollView 组件包装了 UIScrollViewViewController,我想在这个结构中传递页面状态来控制 UIScrollView 的位置我该怎么做? PS代码已更新
  • 那么这应该在 updateUIViewController 函数中处理。你会有这样的东西:@Binding var state: Bool and func updateUIViewController() { bar(newState: state) }
  • 好的,太好了。谢谢!

标签: uikit swiftui


【解决方案1】:

我给你看一个可行的例子。你可以像这样得到一个自然更新的绑定值。

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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-27
    • 2018-08-30
    • 1970-01-01
    • 2022-10-05
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多