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.
Step 1. Create a new Swift project with Storyboard.
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.
Make our life easier name this controller as PeopleArrayController
Click on “Show the Bindings inspector” on top right. Make the changes showed on the picture.
- Bind our new
ArrayController
toViewController
- Set the
Model Key Path
topeopleArray
or the name of the array in yourViewController.swift
.
Step 5. Add Table View from the Library.
By default the Table View comes with 2 rows only, add additionl one for mobile number.
Now, connect the Array Controller and the Table View.
Name the columns of Table View.
As a final step, bind the Table Cell View.
Step 6. Build and Run.
Source code: Github
Sources: