为什么XUIView中的Binding<Bool>看不到更新值?

我有一个SwiftUIXView,它包装了一个XUIView.在XUIView中,我有一个Binding<Bool>,它是用XView@Binding...初始化的.在XUIView中,我有一个UIButton,我使用XUIView中的"绑定"属性来切换customFlag.随着Text的正确更新,这很好地传播到了SwiftUI视图中.然而,UIButton年的S头衔没有得到适当的更新.XUIView._update方法不"看到"新值.

我错过了什么吗? 我是否必须在updateUIView方法中分配CustomFlag才能使其工作?

带有一些打印调用的样例代码,用于查看发生了什么:

import SwiftUI

struct UIKitBindingView: View {
    @State private var customFlag: Bool = false
    var body: some View {
        VStack {
            Text("customFlag: \(customFlag ? "ON" : "OFF")")
            XView(customFlag: $customFlag)
                .frame(width: 200, height: 100)
        }
    }
}

struct UIKitBindingView_Previews: PreviewProvider {
    static var previews: some View {
        UIKitBindingView()
    }
}


struct XView: UIViewRepresentable {
    typealias UIViewType = XUIView
    typealias Context = UIViewRepresentableContext<XView>
    @Binding var customFlag: Bool
    
    init(customFlag: Binding<Bool>) {
        self._customFlag = customFlag
    }

    func makeUIView(context: Context) -> XUIView {
        Swift.print("XView: \(#function)")
        let v = XUIView(frame: .zero, customFlag: $customFlag)
        return v
    }

    func updateUIView(_ uiView: XUIView, context: Context) {
        Swift.print("XView: \(#function)")
        // uiView.customFlag = $customFlag
        Swift.print("XView: \(#function): customFlag: \(customFlag) \n--\($customFlag)")
        uiView._update()
    }
}

class XUIView: UIView {
    weak var button: UIButton?
    var customFlag: Binding<Bool>
    
    init(frame: CGRect, customFlag: Binding<Bool>) {
        self.customFlag = customFlag
        super.init(frame: frame)
        Swift.print("XUIView: \(#function)")
        _configure()
    }
    
    required init?(coder: NSCoder) {
        self.customFlag = Binding(get: { true }, set: { v, t in })
        super.init(coder: coder)
        Swift.print("XUIView: \(#function)")
        _configure()
    }
    
    deinit {
        Swift.print("XUIView: \(#function)")
    }
    
    func _update() {
        Swift.print("XUIView: \(#function): \(customFlag.wrappedValue)\n--\(customFlag)")
        button?.setTitle("BUTTON:" + (customFlag.wrappedValue ? "ON" : "OFF"), for: .normal)
    }
    
    private func _configure() {
        backgroundColor = .yellow
        let b = UIButton()
        button = b
        self.addSubview(b)
        b.translatesAutoresizingMaskIntoConstraints = false
        let cons = [
            self.centerXAnchor.constraint(equalTo: b.centerXAnchor),
            self.centerYAnchor.constraint(equalTo: b.centerYAnchor),
        ]
        NSLayoutConstraint.activate(cons)
        b.setTitleColor(.systemBlue, for: .normal)
        b.addAction(UIAction(handler: { action in
            Swift.print("XUIView: \(#function): button action ***")
            self.customFlag.wrappedValue.toggle()
        }), for: .touchUpInside)
        _update()
    }
}

轻触按钮后的控制台输出:

XUIView: __preview___configure(): button action ***
XView: __preview__updateUIView(_:context:)
XView: __preview__updateUIView(_:context:): customFlag: true 
--Binding<Bool>(transaction: SwiftUI.Transaction(plist: []), location: SwiftUI.LocationBox<SwiftUI.Binding<Swift.Bool>.(unknown context at $10594f2e0).ScopedLocation>, _value: true)
XUIView: __preview___update(): false
--Binding<Bool>(transaction: SwiftUI.Transaction(plist: []), location: SwiftUI.LocationBox<SwiftUI.Binding<Swift.Bool>.(unknown context at $10594f2e0).ScopedLocation>, _value: false)

推荐答案

作为字面意思的Binding<Bool>并不是Binding的正式用法.

绑定应用作@Binding属性包装.

https://developer.apple.com/documentation/swiftui/binding

同样重要的是要注意,绑定符合DynamicProperty,因此它应该仅在也符合DynamicPropertyViewstruct中使用.

在重新计算视图的主体之前,该视图为这些属性赋值.

您可以使用updateUIView从SwiftUI到UIKit通信,也可以使用完成处理程序、共享真值来源、委托等从UIKit到SwiftUI通信.

Swift相关问答推荐

是否有一个Kotlin等价的Swift s @ AddendableReport注释'

如何将泛型函数存储到变量中?

如何在向照片添加文本时定义文本对齐、文本背景的Alpha和在文本之前添加图像

是否可以循环遍历SWIFT子类并访问它们的静态变量S?

为什么这个快速代码不显示文本字段?

使用序列初始化字符串的时间复杂度是多少?

为什么这段Swift读写锁代码会导致死锁?

当字符串包含 \r\n 时,NSRegularExpression 不起作用

Swiftui 按钮依次显示一组图像

如何在 Swift 中对单个单词进行词形还原

引用类型(类)不需要但 struct 需要的可识别 id

调用从 SwiftUI 视图传递到 PageViewController.Coordinator 的函数

在 xcode 13 中的构建之间保持可访问性权限

在 Swift 中将两个字节的 UInt8 数组转换为 UInt16

让我的函数计算数组 Swift 的平均值

如何从元组数组创建字典?

3D touch /强制touch 实现

如何在 SwiftUI 中创建带有图像的按钮?

快速延迟加载属性

Switch 语句中的字符串:String不符合协议IntervalType