Creating NSTableView-based software using Bindings in Swift

I work through Cocoa in a Swift book, and I'm stuck in a chapter on Bindings. The book uses nib files, but I want to do everything programmatically (since I join a command that does not use nibs). The project is to create a table based on a view with two columns, and the contents of the table are tied to the ordered objects of the array controller. The contents of the array controller are tied to an array of Employee objects (Employee has 2 properties, namely the name and salary).

I managed to create the table programmatically, as shown below (one scroll view, one table view, 2 table columns):

let tableWidth = windowWidth! * 0.6
let tableHeight = windowHeight! * 0.8

scrollView = NSScrollView(frame: NSRect(x: windowWidth!*0.05, y: windowHeight!*0.08, width: tableWidth, height: tableHeight))

employeeTable = NSTableView(frame: NSRect(x: 0, y: 0, width: tableWidth, height: tableHeight))
employeeTable?.bind("content", toObject: (self.arrayController)!, withKeyPath: "arrangedObjects", options: nil)

nameColumn = NSTableColumn(identifier: "name column")
nameColumn?.width = tableWidth * 0.4
nameColumn?.headerCell.title = "Name"

raiseColumn = NSTableColumn(identifier: "raise column")
raiseColumn?.width = tableWidth * 0.6
raiseColumn?.headerCell.title = "Raise"

employeeTable?.addTableColumn(nameColumn!)
employeeTable?.addTableColumn(raiseColumn!)
employeeTable?.setDelegate(self)

scrollView?.documentView = employeeTable

, , Cell View. , ? , , .

: , NIB NSTableView, NSTableCellView NSTextField . -, NSTableView , . , tableView . NSTextField NSTableCellView objectValue.name( Employee). , NSTableCellView NSTextField ? ( , )?

+4
1

. , , . stevesilva , tableView:viewForTableColumn:row:, , . NSTableCellView textField, . NSTableCellView, . .

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
}

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")
    }

}
+2

Source: https://habr.com/ru/post/1622664/


All Articles