Reputation: 975
I am having problems getting NSTableView to work with Swift 3 and XCode 8. I have an app with one table and one column in it and trying to add items from NSMutableArray. Here is my code :
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var tableView: NSTableView!
var objects: NSMutableArray! = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
self.objects.add("one")
self.objects.add("two")
self.objects.add("three")
self.objects.add("four")
self.tableView.reloadData()
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return self.objects.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any?
{
let cellView = tableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView
cellView.textField!.stringValue = self.objects.object(at: row) as! String
return cellView
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
However this gives me an error:
*** Illegal NSTableView data source (<NSView: 0x610000120820>). Must implement numberOfRowsInTableView: and tableView:objectValueForTableColumn:row
It looks like boths methods are implemented so I have no idea why I'm getting this error. The dataSource and the delegate for the table view are both set to the man View.
Upvotes: 1
Views: 1990
Reputation: 975
As pbush25 recommended I had to set the delegate and datasource in the code. Also, I switched the TableView mode to 'cell based' and then the final code looks like this:
import Cocoa
class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var tableView: NSTableView!
var objects: NSMutableArray! = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
self.objects.add("one")
self.objects.add("two")
self.objects.add("three")
self.objects.add("four")
tableView.delegate = self
tableView.dataSource = self
}
func numberOfRows(in tableView: NSTableView) -> Int
{
return self.objects.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any?
{
return self.objects.object(at: row)
}
override var representedObject: Any? {
didSet {
}
}
}
Upvotes: 0
Reputation: 930
Your numberOfRows method signature is incorrect for the current macOS SDK. It should be:
func numberOfRows(in tableView: NSTableView) -> Int
Upvotes: 2