updateProperties()的新方法,可以通过修改属性值达到更新 UI 的效果。layoutSubviews()或者viewWillLayoutSubviews()方法)。常见使用场景如下。 setNeedsUpdateProperties()方法手动触发更新。import UIKit
@Observable class Model {
var currentColor: UIColor = .systemGray
var currentValue: String = "WWDC26"
}
class ViewController: UIViewController {
lazy var label: UILabel = {
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 64)
label.center = view.center
return label
}()
let model = Model()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
}
override func updateProperties() {
super.updateProperties()
label.textColor = model.currentColor
label.text = model.currentValue
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
model.currentColor = .systemBlue
model.currentValue = "iOS26"
}
}
import UIKit
class Model {
var currentColor: UIColor = .systemBlue
var currentValue: String = "WWDC26"
}
class ViewController: UIViewController {
lazy var label: UILabel = {
let label = UILabel()
label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 64)
label.center = view.center
return label
}()
let model = Model()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
}
override func updateProperties() {
super.updateProperties()
label.textColor = model.currentColor
label.text = model.currentValue
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
model.currentColor = .systemGray
model.currentValue = "iOS26"
// 手动更新
setNeedsUpdateProperties()
}
}