I'm trying to programmatically populate the cells of a column with images already defined in an array (flags).
In IB I have an Image View directly within a Table Cell View. In the ViewController this is what I'm doing:
public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let cellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else { return nil }
if tableColumn?.title == "flag" {
cellView.imageView?.image = NSImage(named: flags[row]) // NOT WORKING
} else if tableColumn?.title == "country" {
cellView.textField?.stringValue = flags[row].uppercased()
}
return cellView
}
This results in the text field cells in the "country" column getting set fine, but each of the cells in the "flag" column all have the default image I set in IB--or nothing if I take that out.
According to the tutorials and StackOverflow posts I've looked through, it seems that I'm doing everything right--but obviously I've messed up something.
CodePudding user response:
(In response to the screen cast shared in the comments)
Notice how that Image View (in the cell) is not referenced by anything (its "Referencing Outlets" section on the right is empty).
Your image view is a subview of its cell (as indicated by its position in the view heiarchy on the left side bar), so you could presumably access it using something like:
let imageView = cell.subViews.first(where: { $0 is NSImageView }) as! NSImageView
imageView.image = NSImage(named: flags[row])
...but that's obviously clunky.
Instead, you should select your cell, and drag from its imageView
outlet, to the Image View. This will make a new reference, which will make cell.imageView
non-nil.
Alternatively, I would suggest you just delete your cell, and create a new one from the "Image & Test Table Cell View" from the "Object Library". It'll have all the outlets hooked up already.