My Profile Photo

Flying blind - coding nonsense


Strange advantures on the lands of Swift and Cocoa...


KVO, KVC and Bindings

The original tutorial was published in Cocoa Programming for OS X: The Big Nerd Ranch Guide in April, 2015. As far as I know this was last macOS/AppKit/Cocoa book by Aaron Hillegass, later he published only about iOS/UIKit. Although the book was written for Xcode 6.3 and Swift 1.2 it is a very interesting and useful reading in case you are interested in macOS programming.

We will create a simple Thermostat app with minimal code using KVC.

Our final app will look like this. KVC_final

Step 1. Create a Swift project with Storyboard and add the following components:

  • NSSlider
  • Label (NSTextField)
  • 2 x NSButton
  • NSSwitch

to Main.storyboard. KVC1

Step 2. Add a variable to ViewController.swift.

@objc dynamic var temperature: Int = 68

Step 3. Select NSSlider and Click on ‘Show the Bindings Inspector’. In the Value field, set ‘Bind to’ to ‘View Controller’ and set the Model Key Path to ‘temperature’. KVC2

Do not forget to change the Control State to ‘Continous’ on the Attribute inspector. KVC21

Step 4. Select Label(NSTextField) and Click on ‘Show the Bindings Inspector’. In the Value field, set ‘Bind to’ to ‘View Controller’ and set the Model Key Path to ‘temperature’. KVC3

If you run the app now, you can see that changing the slider value will change the value of the NSTextField.

Step 5. Holding ‘CTRL’ connect both NSButtons to ViewController.swift as @IBAction. The code will be very simple to increase or decrease temperature:

 @IBAction func coolerPressed(_ sender: Any) {
        temperature -= 1
    }
  @IBAction func warmerPressed(_ sender: Any) {
        temperature += 1
    }

This time you can change the value of the temperature with buttons as well, not only the slider.

Step 6. We would like to create an ‘ON/OFF’ switch, so we can turn off our thermostat.

Add a Boolean variable to ViewController.swift.

@objc dynamic var isItOn: Bool = true

Select NSSwitch and Click on ‘Show the Bindings Inspector’. In the Value field, set ‘Bind to’ to ‘View Controller’ and set the Model Key Path to ‘isItOn’.

KVC4

Step 7. To make our switch work, we need to bind it to the slider. So select NSSlider and Click on ‘Show the Bindings Inspector’ again, but this time bind the ‘Availability’/’Enabled’ to ‘View Controller’ KVC5

Run the application, using the switch you can disable the slider. KVC5

Source code: Github

Sources:

  1. Nate Chandler, Adam Preble, Aaron Hillegass - Cocoa Programming for OS X: The Big Nerd Ranch Guide
  2. Lucas Derraugh- Cocoa Explorations - Swifty Cocoa Bindings

comments powered by Disqus