Created
April 11, 2020 08:03
-
-
Save andrewvmail/73138c18ed2fb91c66d2fa27ece895d4 to your computer and use it in GitHub Desktop.
Swift Playground
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 presenting user interface | |
import UIKit | |
import PlaygroundSupport | |
class CounterModule: NSObject { | |
var name = "momo" | |
@objc dynamic var count = Int(0) | |
func increment() -> Void{ | |
count = count + 1 | |
} | |
func decrement() -> Void{ | |
count = count - 1 | |
} | |
} | |
class AppState { | |
} | |
class Controller { | |
var appState = AppState() | |
var counterModule = CounterModule() | |
var state = AppState() | |
} | |
var controller = Controller() | |
var c = controller | |
var s = controller.state | |
class MyViewController : UIViewController { | |
@objc var objectToObserve = c.counterModule | |
var observation: NSKeyValueObservation? | |
var observations: [NSKeyValueObservation]? | |
let label2 = UILabel() | |
let label = UILabel() | |
var observers = [NSKeyValueObservation]() | |
func observeModel() { | |
self.observers = [ | |
observe( \.objectToObserve.count, options: [.old, .new]) { (model, change) in | |
self.label.text = String(change.newValue!) | |
}, | |
observe( \.objectToObserve.count, options: [.old, .new]) { (model, change) in | |
self.label2.text = String(change.newValue!) | |
} | |
] | |
} | |
override func loadView() { | |
let view = UIView() | |
view.backgroundColor = .white | |
// let label2 = UILabel() | |
label2.frame = CGRect(x: 150, y: 500, width: 200, height: 20) | |
label2.text = String(controller.counterModule.count) | |
label2.textColor = .black | |
view.addSubview(label2) | |
// let label = UILabel() | |
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20) | |
label.text = "Hello World!" + controller.counterModule.name | |
label.textColor = .black | |
view.addSubview(label) | |
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) | |
button.backgroundColor = .green | |
button.setTitle("Test Button", for: .normal) | |
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) | |
view.addSubview(button) | |
observeModel() | |
self.view = view | |
} | |
@objc func buttonAction(sender: UIButton!) { | |
controller.counterModule.increment() | |
print("Button tapped", controller.counterModule.count) | |
} | |
} | |
// Present the view controller in the Live View window | |
PlaygroundPage.current.liveView = MyViewController() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment