Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/camji55/observation-uikit
Apple Observation framework integration with UIKit
https://github.com/camji55/observation-uikit
Last synced: 14 days ago
JSON representation
Apple Observation framework integration with UIKit
- Host: GitHub
- URL: https://github.com/camji55/observation-uikit
- Owner: Camji55
- Created: 2023-06-09T22:40:39.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-06-09T23:01:53.000Z (over 1 year ago)
- Last Synced: 2025-01-06T13:13:55.473Z (18 days ago)
- Language: Swift
- Homepage:
- Size: 10.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Observation-UIKit
Apple Observation framework integration with UIKit## How it Works
### Declare your object as `@Observable`
```swift
@Observable
final class Counter {
var count = 0
func increment() {
count += 1
}
func decrement() {
count -= 1
}
}
```### Observe and Render the Changes
```swift
class ViewController: UIViewController {@IBOutlet weak var countLabel: UILabel!
let counter = Counter()
override func viewDidLoad() {
super.viewDidLoad()
render()
}
private func render() {
withObservationTracking {
// Any value that's read from the `Observed` class will be automatically tracked for changes.
countLabel.text = "\(counter.count)"
} onChange: { [weak self] in
Task { @MainActor [weak self] in
// Recursivly call this same function any time an `Observed` propery changes to re-render the view.
self?.render()
}
}
}
@IBAction func incrementButtonTapped(_ sender: Any) {
counter.increment()
}
@IBAction func decrementButtonTapped(_ sender: Any) {
counter.decrement()
}
}
```