Created
July 9, 2018 12:26
-
-
Save banjun/0718a5faf94987780560231b4bb56d73 to your computer and use it in GitHub Desktop.
CocoaBinding in code
This file contains hidden or 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
import Cocoa | |
class ViewController: NSViewController { | |
let model = NSMutableDictionary() | |
private(set) lazy var controller: NSObjectController = .init(content: model) | |
let textView1 = NSTextView() | |
let textView2 = NSTextView() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let views: [String: NSView] = ["tv1": textView1, "tv2": textView2] | |
views.values.forEach { | |
$0.translatesAutoresizingMaskIntoConstraints = false | |
view.addSubview($0) | |
} | |
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[tv1]-[tv2(==tv1)]-|", options: [], metrics: nil, views: views)) | |
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[tv1]-|", options: [], metrics: nil, views: views)) | |
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[tv2]-|", options: [], metrics: nil, views: views)) | |
// Cocoa Binding | |
textView1.bind(.attributedString, to: controller, withKeyPath: "content.bodyText", options: [.continuouslyUpdatesValue: true]) | |
textView2.bind(.attributedString, to: controller, withKeyPath: "content.bodyText", options: [.continuouslyUpdatesValue: true]) | |
model["bodyText"] = "initial text" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment