Anfaje
Anfaje

Reputation: 335

Retrieve object from custom UITableViewCell on selection

So I have a UITableView populated with custom UITableViewCell. Every cell is loaded with an object i would like to retrieve upon row selection.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Here I would like to retrieve the object associated with the selected row.

// Object "cell" is inferred as a UITableViewCell, not as CustomTableViewCell :(
var cell = myTableView.cellForRowAtIndexPath(indexPath)

}

As described above, I can't access the CustomTableViewCell in order to get the associated object. Is there another way of doing this?

Upvotes: 0

Views: 297

Answers (3)

natuslaedo
natuslaedo

Reputation: 429

You have to type cast to the class which you have used when constructing the cell.

let cell = myTableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

or

let cell = myTableView.cellForRowAtIndexPath(indexPath) as MyTableViewCellClass

Upvotes: 0

Sebastian
Sebastian

Reputation: 8164

Usually, your UITableView is backed up by a data source, which is e.g. an array. Therefore, use the provided indexPath to get the object from the array.

Apart from that, you can also cast the cell to your custom class:

var cell = myTableView.cellForRowAtIndexPath(indexPath) as CustomTableViewCell

Upvotes: 1

Greg
Greg

Reputation: 25459

You should cast it to CustomTableViewCell, try that:

var cell = myTableView.cellForRowAtIndexPath(indexPath) as CustomTableViewCell

Upvotes: 0

Related Questions