实现两端的数据同步
1. 使用 @Binding 和 Coordinator
struct WAHWDMP4PlayerView: UIViewRepresentable {
@Binding var sources: [String]
@Binding var playerState: PlayerState // 假设这是一个表示播放器状态的枚举
func makeUIView(context: Context) -> WAHWDMP4PlayerOriginView {
let playerView = WAHWDMP4PlayerOriginView()
playerView.delegate = context.coordinator // 设置代理为 Coordinator
return playerView
}
func updateUIView(_ uiView: WAHWDMP4PlayerOriginView, context: Context) {
uiView.updateSources(sources: sources)
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, WAHWDMP4PlayerOriginViewDelegate {
private var parent: WAHWDMP4PlayerView
init(_ parent: WAHWDMP4PlayerView) {
self.parent = parent
}
// 实现委托方法,处理数据变化
func playerStateChanged(to newState: PlayerState) {
parent.playerState = newState // 更新绑定属性
}
}
}
// 假设这是你的 UIKit 视图类
protocol WAHWDMP4PlayerOriginViewDelegate: AnyObject {
func playerStateChanged(to newState: PlayerState)
}
class WAHWDMP4PlayerOriginView: UIView {
weak var delegate: WAHWDMP4PlayerOriginViewDelegate?
// 当播放器状态改变时调用此方法
func changePlayerState(to newState: PlayerState) {
// 更新内部状态逻辑
delegate?.playerStateChanged(to: newState) // 通知 Coordinator
}
// 其他代码...
}2. 使用 @Published 和 ObservableObject
3. 使用 @State 和回调函数
关键点总结
Last updated