Skip to content

Instantly share code, notes, and snippets.

@15458434
Created January 9, 2022 13:15
Show Gist options
  • Save 15458434/805a894b0e31c832f166b6ce2ba57956 to your computer and use it in GitHub Desktop.
Save 15458434/805a894b0e31c832f166b6ce2ba57956 to your computer and use it in GitHub Desktop.
//: A UIKit based Playground for showing KVO in Swift.
import UIKit
import PlaygroundSupport
final class MyViewController : UIViewController {
@objc var model: MyModel = MyModel()
var intValueObserver: NSKeyValueObservation!
weak var label: UILabel!
weak var button: UIButton!
@objc func incrementTouchUpInside(_ sender: UIButton) {
model.increment()
}
func updateLabel() {
self.label.text = "\(model.intValue)"
}
// MARK: UIViewController
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
view.addSubview(label)
self.label = label
label.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: label.topAnchor, constant: -150).isActive = true
view.centerXAnchor.constraint(equalTo: label.centerXAnchor, constant: 0).isActive = true
label.textColor = .black
let button = UIButton()
button.setTitleColor(UIColor.systemBlue, for: .normal)
button.setTitle("Increment", for: .normal)
button.addTarget(self, action: #selector(incrementTouchUpInside(_:)), for: .touchUpInside)
view.addSubview(button)
self.button = button
button.translatesAutoresizingMaskIntoConstraints = false
view.bottomAnchor.constraint(equalTo: button.bottomAnchor, constant: 150).isActive = true
view.centerXAnchor.constraint(equalTo: button.centerXAnchor, constant: 0).isActive = true
self.view = view
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
intValueObserver = self.observe(\.model.intValue, options: [.initial, .new], changeHandler: { mySelf, change in
mySelf.updateLabel()
})
}
override func viewWillDisappear(_ animated: Bool) {
intValueObserver = nil
super.viewWillDisappear(animated)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
final class MyModel: NSObject {
@objc dynamic var intValue: Int = 0
func increment() {
intValue += 1
}
}
@wenh08
Copy link

wenh08 commented Jan 10, 2022

Hi thank you for this, I will try it out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment