How to apply to a subclass in Swift?

I have a UITableView with many different cells based on the fact that in the data source content array they should display user 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 an error

UITableViewCell does not have the attribute customLabel

which has a QuestionTableViewCell . What happened to my cast in QuestionTableViewCell ?

+6
source share
3 answers

The problem is not your actor, but the cell declaration. You declared it as an optional UITableViewCell, and this declaration remains forever - and that’s all the compiler knows.

Therefore, you must point to the customLabel dial customLabel . Instead of this:

 cell.customLabel.text = "test" 

You need the following:

 (cell as QuestionTableViewCell).customLabel.text = "test" 

You can make it easier for yourself by declaring another variable (since you know that in this particular case your cell will be QuestionTableViewCell), but as long as you only have one variable, cell , you have to constantly throw it in any class which, in your opinion, really will be. Personally, I would write something similar to avoid casting again:

  if let questionText = objectAtIndexPath as? String { let qtv = tableView.dequeueReusableCellWithIdentifier("questionCell", forIndexPath: indexPath) as QuestionTableViewCell qtv.customLabel.text = "test" cell = qtv } 
+22
source

The problem is this var cell : UITableViewCell? = nil var cell : UITableViewCell? = nil . Do you declare it as a UITableViewCell? and he has this type forever.

You can declare another variable

 let questionCell = cell as! QuestionTableViewCell questionCell.customLabel.text = "test" 
+1
source

You can do any of the following:

  • replace: cell.customLabel.text = "test"

    with

     cell?.customLabel.text = "text1" 
  • change var cell : UITableView? = nil var cell : UITableView? = nil on var cell : UITableView!

-5
source

Source: https://habr.com/ru/post/976904/


All Articles