Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-11-28 05:43:52

I have UITextView implemented by UIViewRepresentable.

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
        
    }}

I want to use it like this.

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)
                    
            }
    }
}

On iOS 13 if I tap the button, updateUIView is called and change that text color but on iOS 14 updateUIView isn't called. Are there any way to call view update by changing ObservedObject on iOS 14?

And here codes of TmpTextViewModel and its model.

    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
    
}

Questioner
harunaga
Viewed
0
Patrick Sturm 2020-11-28 15:13:57

You need to make ˋCustomTextViewˋ to listen to changes of ˋTmpTextViewModelˋ.

Just declare ˋtmpTextVMˋ in ˋCustomTextViewˋ as ˋ@ObservedOjectˋ.

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