假设您有一个遗留的视图控制器,我想在SwiftUI中使用它。视图控制器有一个@Published属性,该属性包含它的当前状态:
class LegacyViewController: UIViewController {
enum State {
case opened
case closed
case halfOpened
}
@Published var state: State
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.state = .closed
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// state is changed after some time
}
}理想情况下,我希望在SwiftUI中使用它,如下所示:
struct ContentView: View {
@State var state: LegacyViewController.State
var body: some View {
VCWrapper(state: $state).overlay (
Text("\(state)")
)
}
}这意味着我需要实现UIViewControllerRepresentable协议:
struct VCWrapper: UIViewControllerRepresentable {
@Binding var state: LegacyViewController.State
func makeUIViewController(context: Context) -> LegacyViewController {
let vc = LegacyViewController(nibName: nil, bundle: nil)
/// where to perform the actual binding?
return vc
}
func updateUIViewController(_ uiViewController: LegacyViewController, context: Context) {
}
}但是,我在找出从LegacyViewController的state属性到VCWrapper公开的state属性的实际绑定位置时遇到了麻烦。如果LegacyViewController公开了一个委托,我可以通过Coordinator对象实现绑定,但考虑到我没有使用委托对象,我不确定如何做到这一点?
发布于 2020-10-15 00:51:12
以下是可能的解决方案--使用Combine。使用Xcode12/ iOS 14进行了测试。
import Combine
struct VCWrapper: UIViewControllerRepresentable {
@Binding var state: LegacyViewController.State
func makeUIViewController(context: Context) -> LegacyViewController {
let vc = LegacyViewController(nibName: nil, bundle: nil)
// subscribe to controller state publisher and update bound
// external state
context.coordinator.cancelable = vc.$state
.sink {
DispatchQueue.main.async {
_state.wrappedValue = $0
}
}
return vc
}
func updateUIViewController(_ uiViewController: LegacyViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator {
var cancelable: AnyCancellable?
}
}https://stackoverflow.com/questions/64357436
复制相似问题