1

I want to put 2 custom cell in TableView, but I have a small problem with it. I tried to find answer in Google and StackOverflow, but answers can't help me.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.row == 0{
        var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("FistCustomTableViewCell", forIndexPath: indexPath) as CustomCell
        //set cell2
    }
    if indexPath.row >= 1{
        var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as CustomCell
        let cons = aArray[indexPath.row - 1]
        // set cell2 
    }
    return cell // (!) Use of unresolved identifier "cell"
}
Josh Burgess
  • 9,327
  • 33
  • 46
Maxim Globak
  • 21
  • 1
  • 4

2 Answers2

5

You need to draw the cell declaration outside:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  var cell: CustomCell!
  if indexPath.row == 0{
    cell = tableView.dequeueReusableCellWithIdentifier("FistCustomTableViewCell", forIndexPath: indexPath) as CustomCell
    //set cell2
  }
  if indexPath.row >= 1{
    cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as CustomCell
    let cons = aArray[indexPath.row - 1]
    // set cell2 
  }
  return cell
}
qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • Individually, everything works, the cell is described in the right class, but when I tried to connect all, I have failed. – Maxim Globak Feb 18 '15 at 16:40
  • It's out of scope when you declare it inside the `if` statements – qwerty_so Feb 18 '15 at 16:42
  • In this case: where "return cell" // (!) variable "Cell" used before being initialized – Maxim Globak Feb 18 '15 at 16:48
  • Bloody Swift. Just give it an init like `var cell = CustomCell()` or use an optional. See my added "!" – qwerty_so Feb 18 '15 at 16:50
  • @ThomasKilian I have a similar requirement in my project, need to display 2 different cells in a table. I am trying to show them by defining 2 prototypes in a table. but it is not working. This is the link that I have followed: http://stackoverflow.com/questions/30774671/uitableview-with-more-than-one-custom-cells-with-swift – Dee Sep 15 '16 at 16:03
  • @ThomasKilian could you please guide me – Dee Sep 15 '16 at 16:03
  • @ThomasKilian I have posted a query. Here is the link: http://stackoverflow.com/questions/39515763/how-to-show-2-customized-cells-in-the-uitableview – Dee Sep 15 '16 at 16:11
  • @Dee The whole process is quite complex and I needed a couple of YT tutorials first. Finally I reduced the TableViewPlayground example from Apple to the minimum I needed. Once I grasped that I started creating a simple sandbox on my own to play around. – qwerty_so Sep 15 '16 at 18:36
1

You have to declare the cell out of the if statement.

gasho
  • 1,926
  • 1
  • 16
  • 20