iOS 14 SwiftUI UIViewRepresentable updateUIView 没有检测到 ObservedObject 变化?

iOS 14 SwiftUI UIViewRepresentable updateUIView doesn't detect ObservedObject changing?

我已经通过 UIViewRepresentable 实现了 UITextView。

struct CustomTextView: UIViewRepresentable {
    var tmpTextVM: TmpTextViewModel
    
    func makeUIView(context: UIViewRepresentableContext<CustomTextView>) -> UITextView {
        let textView = UITextView()
        textView.backgroundColor = UIColor.clear
        textView.isScrollEnabled = false
        textView.text = "aaaaaaaaaaaaaaaaaa"
        textView.font = UIFont(name: "ArialMT", size: 20)
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.textColor = tmpTextVM.color
        
    }}

我想这样用

struct ContentView: View {
    
    @ObservedObject var tmpTextVM: TmpTextViewModel
   
        var body: some View {

            VStack {
                
                Button(action: {
                    tmpTextVM.changeColor(UIColor.red)
                }){
                    Image(systemName:"eyedropper.full")
                }
                
                CustomTextView(tmpTextVM: tmpTextVM)
                    .foregroundColor(Color(tmpTextVM.color))
                    .frame(width:300, height: 300, alignment: .topLeading)
                    .border(Color.red, width: 1)
                    
            }
    }
}

在 iOS 13 上,如果我点击按钮,将调用 updateUIView 并更改该文本颜色,但在 iOS 14 上,不会调用 updateUIView。有没有办法通过在 iOS 14 上更改 ObservedObject 来调用视图更新?

这里是 TmpTextViewModel 及其模型的代码。

    class TmpTextViewModel: ObservableObject {
    
    @Published private var tmpTextModel: TmpTextModel = TmpTextModel()
    
    var color: UIColor {tmpTextModel.color}
    
    func changeColor(_ color: UIColor) {
        tmpTextModel.color = color
    }
    
}
struct TmpTextModel {
    
   var color:UIColor = UIColor.purple
    
}

您需要让 ˋCustomTextViewˋ 监听 ˋTmpTextViewModelˋ 的变化。

只需在ˋCustomTextViewˋ中声明ˋtmpTextVMˋ为ˋ@ObservedOjectˋ即可。

struct CustomTextView: UIViewRepresentable {
   @ObservedObject var tmpTextVM: TmpTextViewModel
   //....
}