iphaaw
iphaaw

Reputation: 7204

Could not cast value of type 'NSTableCellView' to 'NSTableViewTest'

I'm trying to set up a custom class for an NSTableView and seem to be almost there with it.

When I run this code I get an error message : Could not cast value of type 'NSTableCellView' (0x7fff7a859af0) to 'NSTableViewTest.MyCellView' (0x10001e480) in the line "let cell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! MyCellView!"

import Cocoa

class Table1: NSTableView, NSTableViewDataSource, NSTableViewDelegate
{

    override func drawRect(dirtyRect: NSRect)
    {
        super.drawRect(dirtyRect)
    }

    func numberOfRowsInTableView(tableView: NSTableView) -> Int
    {
        return 10
    }

    func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
    {
        return 25
    }

    func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
    {
        let cell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self)  as! MyCellView!
        return cell
    }

}

with my cell class defined as :

import Cocoa

class MyCellView: NSView 
{
    @IBOutlet weak var itemName: NSTextField!
    @IBOutlet weak var itemDescription: NSTextField!
    @IBOutlet weak var itemImage: NSImageView!

}

Upvotes: 0

Views: 786

Answers (4)

Monty
Monty

Reputation: 117

You may also need to register the nib file in the ViewController which can be done in viewDidLoad().

let nib = NSNib(nibNamed: "MyCellView", bundle: Bundle.main)
myTableView.register(nib!, forIdentifier: "MyCellView")

Upvotes: 2

PoolHallJunkie
PoolHallJunkie

Reputation: 1363

tableColumn!.identifier should be a String , eg. "cell". The String , after selecting the Prototype cell in the Storyboard, should match the identifier.

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
    let cell = tableView.makeViewWithIdentifier("cell", owner: self)  as! MyCellView!
    return cell
}

enter image description here

Upvotes: 1

Bigman
Bigman

Reputation: 1473

The problem is the identifier you use. tableColumn!.identifier This is a column's identifier, but you want to generate a NSView for a cell view.

   1. Go to the storyboard and select a cell view
   2. associate it with MyCellView (set it in the identity inspector)
   3. specify an identifier in the storyboard (set it in the identity inspector)
   4. Modify the identifier in the code. It should be some string like "MyCellView"

Upvotes: 1

Icaro
Icaro

Reputation: 14845

Your MyCellView class is of NSView, change it to be of type NSTableCellView, as you cant cast NSView to be a NSTableCellView.

I hope that helped you!

Upvotes: 0

Related Questions