I have a UITableView
with a lot of different cells, based on whats in the content array of the datasource they should show custom content.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell? = nil
let objectAtIndexPath: AnyObject = contentArray![indexPath.row]
if let questionText = objectAtIndexPath as? String {
cell = tableView.dequeueReusableCellWithIdentifier("questionCell", forIndexPath: indexPath) as QuestionTableViewCell
cell.customLabel.text = "test"
}
return cell!
}
Here I get the error that
UITableViewCell does not have the attribute customLabel
which QuestionTableViewCell
does have. Whats wrong with my cast to QuestionTableViewCell
?
The problem is not your cast but your declaration of cell
. You declared it as an optional UITableViewCell and that declaration remains forever - and is all that the compiler knows.
Thus you must cast at the point of the call to customLabel
. Instead of this:
cell.customLabel.text = "test"
You need this:
(cell as QuestionTableViewCell).customLabel.text = "test"
You could make this easier on yourself by declaring a different variable (since you know that in this particular case your cell will be a QuestionTableViewCell), but as long as you are going to have just one variable, cell
, you will have to constantly cast it to whatever class you believe it really will be. Personally, I would have written something more like this, exactly to avoid that repeated casting:
if let questionText = objectAtIndexPath as? String {
let qtv = tableView.dequeueReusableCellWithIdentifier("questionCell", forIndexPath: indexPath) as QuestionTableViewCell
qtv.customLabel.text = "test"
cell = qtv
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With