简体   繁体   中英

Binding a NSTableView column titles to an array

I'm trying to understand how binding works. I'm trying to bind columns of a NSTableView to an array which contain the column titles.

When I try the code on Swift Playground, I get an EXC_BAD_INSTRUCTION error. What am I doing wrong?

import AppKit

let titles = ["Title 1", "Title 2"]
let tv = NSTableView()
tv.addTableColumn(NSTableColumn())
tv.addTableColumn(NSTableColumn())
(tv.tableColumns as NSArray).bind(.title, to: titles, withKeyPath: "", options: nil)

I'm trying to understand how binding works.

I'd highly recommend to read the Introduction to Cocoa Bindings Programming Topics . This assumes you're familiar with the following topics as well:

I'm trying to bind columns of a NSTableView to an array which contain the column titles.

Cocoa Bindings Reference:

NSTableView doesn't have any column related binding. The closest one is the content binding, but it's about content, not column header titles, etc.

NSArray & KVC:

There's no way to use self[0] as a key path to get a first item, etc. There're some collection operators you can use on NSArray , but nothing like you need.

let titles = NSArray(arrayLiteral: "Title 1", "Title 2")
titles.value(forKeyPath: "self")   // ["Title 1", "Title 2"]
titles.value(forKeyPath: "@count") // 2

When you read all these linked articles, you'd come up with something like this:

let titles = ["Title 1", "Title 2"]
tableView.tableColumns.enumerated().forEach { (idx, column) in
    column.bind(.headerTitle, to: titles[idx], withKeyPath: "self", options: nil)
}

And it doesn't make much sense to use bindings in this way. Just set the title:

let titles = ["Title 1", "Title 2"]        
for (column, title) in zip(tableView.tableColumns, titles) {
    column.headerCell.title = title
}

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