You can, here is a very simplified example
// Apple documentation
// https://developer.apple.com/documentation/observation
@Observable
class A {
var name = "Nothing Here Yet"
@ObservationIgnored var age = 0
}
class ViewController: UIViewController {
var a = A()
var lbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupLabel()
track()
a.name = "Hello World"
}
func track() {
withObservationTracking {
let _ = self.a.name
} onChange: {
Task { @MainActor [weak self] in
self?.lbl.text = self?.a.name
}
}
}
func setupLabel() {
lbl = UILabel(frame: CGRect(x: 135, y: 300, width: 300, height: 44))
lbl.text = a.name
self.view.addSubview(lbl)
}
}
Topic:
UI Frameworks
SubTopic:
UIKit
Tags: