【发布时间】: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) }
-
好的,太好了。谢谢!