简体   繁体   中英

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

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
    
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM