Very simple view-based NSTableView in Swift

It is widely known that while the internet is full with iOS tutorials you hardly find any Cocoa ones. Many things on iOS with CocoaTouch is simpler than on OS X, so it is not obvious that after reading some tutorials, you will be able code on both platform.

I’d like to share what I learn helping others and receiving advises from experienced fellows. My first application is a simple phonebook using view-based NSTableView. On the internet you can find plenty cell-based NSTableView tutorials with single column using NSArray.

This is what we are building.

Create a Cocoa Application project.

Give a name.

Add NSTableView to the Main Storyboard.

Increase the number of columns from 2 to 3.

Click on the header and name the columns

We need to add identifier to the columns and cells.

You should repeat this to the Last name(lastName) and Mobile number(mobileNumber) columns and cells as well.

Create an IBOutlet and connect it to your tableview but don’t forget the dataSource and delegate either.

@IBOutlet var tableView: NSTableView!

The rest of it is very easy now. Let’s have a NSDictionary:

@IBOutlet var tableView: NSTableView!

In the viewDidLoad() function we need to add elements:

data = [
 [
  “firstName” : “Andrew”,
  “lastName” : “Lyod”,
  “mobileNumber” : “5532612”
 ],
 [
  “firstName” : “Gabriel”,
  “lastName” : “Bota”,
  “mobileNumber” : “54329987”
 ],
 [
  “firstName” : “Olga”,
  “lastName” : “Morales”,
  “mobileNumber” : “53122543”
 ]
]

We need to tell how many rows we will have:

func numberOfRowsInTableView(tableView: NSTableView) -> Int {
 return (data?.count)!
}

We would like to match the NSDictionary key to the column identifier and give the NSDictionary value to the cell.

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
 let item = (data!)[row]
 let cell = tableView.makeViewWithIdentifier((tableColumn!.identifier), owner: self) as? NSTableCellView
 cell?.textField?.stringValue = item[(tableColumn?.identifier)!]!
 return cell
}

It is very important that your NSDictionary keys must match with the identifiers of your columns otherwise it won’t work.

I copy the full code here below.

You can find the source code on Github.