简体   繁体   中英

NSTableView does not call function

I am trying to populate a simply view based NSTableView in a macOS application. I have set the delegate and datasource on the storyboard. I have added this little extension language. When I load the view, func numberOfRows is called and those are added to the tableView, but the function to build the cell value is never called.

I am not sure I have this correct for NSTableView but this basic code works great for iOS apps. I am new to Swift and just cannot seem to get this to work properly.

Any advice?

extension LAManagerVC: NSTableViewDataSource, NSTableViewDelegate {

    func numberOfRows(in tableView: NSTableView) -> Int {
        print ("My Activity Count: \(myActivities.count)")
        return myActivities.count
    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any?{

        print ("Hello world")
        let cell = tableView.make(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
        cell?.textField?.stringValue = myActivities[row].title
        return cell
    }

}

Problem

From the Documentation :

table​View(_:​object​Value​For:​row:)​ 

Called by the table view to return the data object associated with the specified row and column.

Solution

To display the cells use table​View(_:​view​For:​row:​) like this in your case:

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  print ("Hello world")
  let cell = tableView.make(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
  cell?.textField?.stringValue = myActivities[row].title
  return cell
}

objectValueFor is supposed to return the item of the data source array for that specific row (and column), but never a cell:

func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
    return myActivities[row]
}

If you are using Cocoa bindings, bind the UI elements to key path objectValue.<property> , if not implement tableView:viewFor:row: and set the values of the UI elements there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM