Updating views automatically with observation tracking
Use Swift Observation and AppKit’s automatic tracking to update your views in response to model data updates.
Overview
Swift Observation provides the Observable macro to mark your models for automatic change tracking. When you combine Observable models with AppKit, the system automatically watches for property changes and updates your views. You don’t need to manually invalidate anything — AppKit handles it for you.
AppKit provides methods in several objects where automatic observation tracking happens. In a view subclass, updateConstraints() and layout() are examples of two methods that automatically track any Observable properties you read, and AppKit updates your views when those properties change.
Update view properties automatically
The viewWillLayout() method automatically tracks Observable properties and updates views when they change. For example, to show a message list with a status label that displays unread message information, start by creating an Observable model with the properties your view needs:
@Observable
class MessageModel {
var showStatus: Bool
var statusText: String
}Then, use these properties in your view controller’s viewWillLayout() method:
override func viewWillLayout() {
super.viewWillLayout()
statusLabel.alpha = model.showStatus ? 1.0 : 0.0
statusLabel.text = model.statusText
}When the view first appears, AppKit runs viewWillLayout() and tracks that you read showStatus and statusText. If either property changes later, AppKit automatically runs viewWillLayout() again to update the label.
You can also automatically track changes in a custom view using layout().