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
//....
}
Thanks ! This works fine! I don't understand why it was working on iOS13 tho...
I guess this is due to optimizations of the SwiftUI engine.
Ok, I see! Thanks for your help!!