Skip to content

Instantly share code, notes, and snippets.

@banjun
Created July 9, 2018 12:26
Show Gist options
  • Save banjun/0718a5faf94987780560231b4bb56d73 to your computer and use it in GitHub Desktop.
Save banjun/0718a5faf94987780560231b4bb56d73 to your computer and use it in GitHub Desktop.
CocoaBinding in code
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