Create view based NSTableView programmatically using Bindings in Swift

馋奶兔 提交于 2019-11-29 07:52:31
RookiePro

I am answering my own question. Note that I am a beginner and do not know if this is the right way to do things. As noted by user stevesilva in the comments of the above question, I had to implement the delegate method tableView:viewForTableColumn:row: to ensure that the table is view based. Within the delegate method I tried to create a NSTableCellView and bind the textField property but this did not work. I had to subclass NSTableCellView, create a new text field property and then bind that property. This is how my delegate eventually looked.

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {

    let frameRect = NSRect(x: 0, y: 0, width: tableColumn!.width, height: 20)

    let tableCellView = MyTableCellView(frame: frameRect)

    if tableColumn?.identifier == "name column" {
        tableCellView.aTextField?.bind("value", toObject: tableCellView, withKeyPath: "objectValue.name", options: nil)
    } else if tableColumn?.identifier == "raise column" {
        tableCellView.aTextField?.bind("value", toObject: tableCellView, withKeyPath: "objectValue.raise", options: nil)
    }

    return tableCellView
}

And this is my subclassed NSTableCellView:

class MyTableCellView: NSTableCellView {

    var aTextField: NSTextField?

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        aTextField = NSTextField(frame: frameRect)
        aTextField?.drawsBackground = false
        aTextField?.bordered = false
        self.addSubview(aTextField!)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

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