View-Based NSTableView in Swift - How to

做~自己de王妃 提交于 2019-12-03 14:12:31

After hours of search, I discovered this method that works !

func tableView(tableView: NSTableView, viewForTableColumn: NSTableColumn, row: Int) -> NSView
{
    var cell = tableView.makeViewWithIdentifier("List", owner: self) as NSTableCellView
    cell.textField.stringValue = "Hey, this is a cell"
    return cell;
}

I see that you found your answer your self but from what I can see your clue was in the Return Value of Objective -C delegate.

- (NSView *)tableView:...

The return value is a NSView.

But you should look at the Swift/Objective -c documentaion.

From the Docs:

Providing Views for Rows and Columns tableView:viewForTableColumn:row:

Asks the delegate for a view to display the specified row and column.

Declaration
SWIFT
@optional func tableView(_ tableView: NSTableView!,
      viewForTableColumn tableColumn: NSTableColumn!,
                     row row: Int) -> NSView!
OBJECTIVE-C
- (NSView *)tableView:(NSTableView *)tableView
   viewForTableColumn:(NSTableColumn *)tableColumn
                  row:(NSInteger)row

Note the -> NSView! in the swift code also.

The new docs allow you to see the code for Swift and Objective -c side by side or one or the other. You can use a selection tab at the top of the documentation to choose.

It also looks like your code should include the "!" for optionals

Martin

If you change the content mode of the table view from view based to cell based the method is called.

This beat me up for an hour. Works with Swift 2.2, probably won't work for earlier or later versions:

 let cell = tableView.makeViewWithIdentifier(myid!, owner: nil)  // You can't cast this with as! like they want you to

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