Swift Create NSTableView programatically

Swift Create NSTableView programatically

In this article we will create a NSTableView programmatically in Swift

//  TableViewFromCodeWindowController.swift
//  SwiftTableViews
//  Created by Debasis Das on 25/01/16.
//  Copyright © 2016 Knowstack. All rights reserved.

import Cocoa

class TableViewFromCodeWindowController: NSWindowController,NSTableViewDataSource, NSTableViewDelegate {

    let columnDefaultWidth:Float = 100.0
    //List of Table Columns Metadata that will be used to create the tableview programatically
    let tableViewColumnNamesArray: NSArray = [
        ["columnIdentifier":"firstName","columnTitle":"First Name","columnType":"text","columnMaxWidth":500,"columnMinWidth":50],
        ["columnIdentifier":"lastName","columnTitle":"Last Name","columnType":"text","columnMaxWidth":500,"columnMinWidth":50],
        ["columnIdentifier":"fullTimeEmployee","columnTitle":"Full Time Employee","columnType":"check","columnMaxWidth":500,"columnMinWidth":50]
    var dataArray:NSMutableArray = []
    @IBOutlet weak var tableView: NSTableView?
    override func windowDidLoad() {
        self.dataArray = NSMutableArray(array: self.createTestData())

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    override func awakeFromNib() {

        for var columnDictionary  in self.tableViewColumnNamesArray {
            let tColumn:NSTableColumn = NSTableColumn(identifier: columnDictionary["columnIdentifier"]! as! String)
            tColumn.headerCell.title = columnDictionary["columnTitle"]! as! String
            //Float to CGfloat conversion is required
            tColumn.width = CGFloat(columnDefaultWidth)
            tColumn.minWidth = CGFloat(columnDictionary["columnMinWidth"]! as! Float)
            tColumn.maxWidth = CGFloat(columnDictionary["columnMaxWidth"]! as! Float)
           if (columnDictionary["columnType"] as! String == "check"){
                let checkBox = NSButtonCell()
                checkBox.title = ""
                checkBox.alignment = .Right
                tColumn.dataCell = checkBox
            //else use the default text field cell
            //Applying sort descriptors to each column
            let sortDescriptor = NSSortDescriptor( key: columnDictionary["columnIdentifier"]! as? String, ascending: true, selector: Selector("compare:"))
            tColumn.sortDescriptorPrototype = sortDescriptor



        self.tableView?.usesAlternatingRowBackgroundColors = true
        self.tableView?.columnAutoresizingStyle = .UniformColumnAutoresizingStyle
     func removeAllTableColumn()
        let tColCount = self.tableView!.tableColumns.count
        if tColCount > 0
            for var i = 0; i < tColCount; i++
    //Demo data is created here
    func createTestData() -> NSArray
        return [

    func numberOfRowsInTableView(aTableView: NSTableView!) -> Int
        let numberOfRows:Int = self.dataArray.count
        return numberOfRows
    func tableView(tableView: NSTableView!, objectValueForTableColumn tableColumn: NSTableColumn!, row: Int) -> AnyObject!
        let object = self.dataArray[row]
        return object[tableColumn.identifier]

    func tableView(tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor])

The sample code can be downloaded here

Posted in Swift Tagged with: , , ,
4 comments on “Swift Create NSTableView programatically
  1. heimi says:

    Thanks for the code
    It seems to be incompatible with Swift3 / Xcode8, even after conversion.
    In awakeFromNib(), the line
    let tColumn:NSTableColumn = NSTableColumn(identifier: columnDictionary[“columnIdentifier”]! as! String)
    gives the error
    Type NSFatEnumerationIterator.Element (aka’Any’) has no subscript members

    any ideas?

  2. anon says:

    The title is a bit of a misnomer, as this isn’t an NSTableView created programatically. The table view is already in IB and loaded from nib, then configured programatically.

    • Debasis Das says:

      agreed, Thanks for pointing it out, I have a sample where even a NSTableView is created programmatically and added to an encompassing view. Will update this post with the second sample shortly.

Leave a Reply

Your email address will not be published. Required fields are marked *