How to add columns in Cocoa NSTableView?

倖福魔咒の 提交于 2019-11-29 13:02:52

Bingo ! Thanks to Willeke I rewrote my code as follows :

var donnees: DataFrame = DataFrame()    // Some table-like data with unspecified number of columns

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    initData()      // get the actual data
    self.setTableColumns() // and prepare the columns accordingly
}
    func setTableColumns() {
    // In Interface Builder I've prepared a cell view in the 0-th tableColumn and set the identifier of this NSTableColumn to "ModelCellView"
        let myCellViewNib = dataTable.registeredNibsByIdentifier!["ModelCellView"]   // I save the cellView's Nib
    //      Make the ad-hoc number of columns
        if donnees.nbCol > 0 {
            for k in 0..<donnees.nbCol {
                let newColumn = NSTableColumn(identifier: idArray[k])       // idArray : [String] of unique identifiers
                dataTable.addTableColumn(newColumn)
                dataTable.registerNib(myCellViewNib, forIdentifier: newColumn.identifier)  // I register the above Nib for the newly added tableColumn
            }
            dataTable.removeTableColumn(dataTable.tableColumns[0])  // remove the original column, now unnecessary
        }
    }

extension MyViewController : NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
    return self.donnees.nbRow
}  
extension MyViewController : NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let columnID = tableColumn!.identifier
    let cellView = tableView.makeViewWithIdentifier(columnID, owner: self) as! NSTableCellView
    cellView.textField?.stringValue = "theActualCellData"
    return cellView
}  

And it works perfectly as intended. Again, thanks to Willeke.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!