I think Cocoa Bindings is a little bit controversial technology. Some people believe less code means less error, easier to debug, according to the others it is hard to read and understand, it’s black magic. During the years I tried to understand several times with very little luck. Last night I read a brilliant book by Stuart Grimshaw. I highly recommend his book, he wrote a lot of very useful concept about general programming and Swift coding as well.

This tutorial shows a simple Table View. final

Step 1. Create a new Swift project with Storyboard. create

Step 2. Add a new file with a Person class, which conforms KVO.

import Foundation

class Person: NSObject {
    @objc dynamic var firstName: String
    @objc dynamic var lastName: String
    @objc dynamic var mobileNumber: String
    
    init(firstName: String, lastName: String, mobileNumber: String) {
        self.firstName = firstName
        self.lastName = lastName
        self.mobileNumber = mobileNumber
    }
}

Step 3. Create an array in ViewController.swift as data source of the TableView. This will be the last code we need to write.

@objc dynamic var peopleArray: [Person] = [
											Person(firstName: "Ragnar", 
													lastName: "Lothbrok", 
													mobileNumber: "555-1234"),
                                            Person(firstName: "Bjorn", 
                                            		lastName: "Lothbrok", 
                                            		mobileNumber: "555-3412"),
                                            Person(firstName: "Harald", 
                                               		lastName: "Finehair", 
                                               		mobileNumber: "555-4512")]

Step 4. Move to Main.storyboard and add an ArrayController from the library. arraycontroller

Make our life easier name this controller as PeopleArrayController naming

Click on “Show the Bindings inspector” on top right. Make the changes showed on the picture.

  • Bind our new ArrayController to ViewController
  • Set the Model Key Path to peopleArray or the name of the array in your ViewController.swift.

inspector

Step 5. Add Table View from the Library. tableview

By default the Table View comes with 2 rows only, add additionl one for mobile number. tableview3rows

Now, connect the Array Controller and the Table View. tableviewarraycontroller

Name the columns of Table View. columns

As a final step, bind the Table Cell View. tablecellview

Step 6. Build and Run. final

Source code: Github

Sources:

  1. Stuart Grimshaw - Mastering macOS Programming
  2. Thomas Grossen - TableView binding with Swift 4 and Storyboard
  3. Taun Chapman - Bindings, the Best Code is the Code Not Written