Created
January 9, 2022 13:15
-
-
Save 15458434/805a894b0e31c832f166b6ce2ba57956 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi thank you for this, I will try it out