2015-05-12 3 views
3

Уверен, что этот вопрос задан раньше, но я не могу найти ответ, который решает мою проблему с вложенной логикой if-else и switch-case.
У меня есть UITableView с двумя разделами, каждая секция имеет две пользовательские ячейки. Вот и все. 4 клетки. Но независимо от того, что я делаю, я получаю «Missing возвращения в функции, как ожидается, вернется UITableViewCell»Отсутствует return UITableViewCell

Вопроса Как я могу изменить эту установку, так что я получаю заявление еще на дне, который удовлетворит быструю логику?

Любая помощь будет очень признателен

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

    if indexPath.section == 0{ 

     switch (indexPath.row) { 
     case 0: 
      let cell0: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! SettingsCell 
     cell0.backgroundColor = UIColor.redColor() 
     break 

     case 1: 
      let cell1: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! SettingsCell 
     cell1.backgroundColor = UIColor.whiteColor() 
     break 

     default: 
      break 
     } 
    } 

    if indexPath.section == 1{ 

     switch (indexPath.row) { 
     case 0: 
      let cell10: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell10", forIndexPath: indexPath) as! SettingsCell 
     cell10.backgroundColor = UIColor.redColor() 
     break 

     case 1: 
      let cell11: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell11", forIndexPath: indexPath) as! SettingsCell 
     cell11.backgroundColor = UIColor.whiteColor() 
     break 

     default: 
      break 

     } 
    } 
} 
+0

что вы хотите выполнить ...? –

+0

Что вы подразумеваете под этим. Я хочу tableView с двумя разделами, каждая с двумя ячейками. – KML

+1

@karlml написать. return cell statement в методе cellForRowAtIndexPath –

ответ

9
  • Декларация е клетка в начале метода,
  • присвоить значение ячейки в зависимости от раздела и номер строки,
  • бросить fatalError() во всех случаях, что «не должно происходить»,
  • возвращение клетки.

Также обратите внимание, что инструкции break не нужны. По умолчанию поведение в Swift: не, чтобы перейти к следующему случаю.

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

    let cell: SettingsCell 

    switch(indexPath.section) { 
    case 0: 
     switch (indexPath.row) { 
     case 0: 
      cell = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.redColor() 

     case 1: 
      cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.whiteColor() 

     default: 
      fatalError("Unexpected row \(indexPath.row) in section \(indexPath.section)") 
     } 
    case 1: 
     switch (indexPath.row) { 
     case 0: 
      cell = tableView.dequeueReusableCellWithIdentifier("cell10", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.redColor() 

     case 1: 
      cell = tableView.dequeueReusableCellWithIdentifier("cell11", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.whiteColor() 

     default: 
      fatalError("Unexpected row \(indexPath.row) in section \(indexPath.section)") 

     } 
    default: 
     fatalError("Unexpected section \(indexPath.section)") 

    } 
    return cell 
} 

Функция fatalError() ошибки помечаются как @noreturn, поэтому компилятора знает, что выполнение программы не будет продолжаться от случаев по умолчанию. (Это также помогает найти логические ошибки в программе.)

Компилятор проверяет, что значение присваивается cell во всех других случаях.

возможность инициализировать постоянной (let cell ...) в этом способом является новым в Swift 1.2.


В качестве альтернативы вы можете создать ячейку и вернуть его «немедленно» в каждом конкретном случае:

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

    switch(indexPath.section) { 
    case 0: 
     switch (indexPath.row) { 
     case 0: 
      let cell = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.redColor() 
      return cell 

     case 1: 
      let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.whiteColor() 
      return cell 

     default: 
      fatalError("Unexpected row \(indexPath.row) in section \(indexPath.section)") 
     } 
    case 1: 
     switch (indexPath.row) { 
     case 0: 
      let cell = tableView.dequeueReusableCellWithIdentifier("cell10", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.redColor() 
      return cell 

     case 1: 
      let cell = tableView.dequeueReusableCellWithIdentifier("cell11", forIndexPath: indexPath) as! SettingsCell 
      cell.backgroundColor = UIColor.whiteColor() 
      return cell 

     default: 
      fatalError("Unexpected row \(indexPath.row) in section \(indexPath.section)") 

     } 
    default: 
     fatalError("Unexpected section \(indexPath.section)") 
    } 
} 

Опять же, называя fatalError() решает «недостающее возвращение ожидаемого» компилятор ошибка.

Этот шаблон может быть полезен, если в каждом случае созданы различные типы ячеек (с разными классами).

+0

Эта авария: фатальная ошибка: неожиданно найденное значение nil при развертывании Опциональное значение в строке: return cell – KML

+0

Но он компилируется сейчас? - Вы подтвердили, что 'dequeueReusableCellWithIdentifier' возвращает действительную ячейку? Вы назвали 'registerNib (..)' или 'registerClass (...)' или вы определили ячейки прототипа в Storyboard (для всех идентификаторов ячеек)? –

+0

Все мои прототипные ячейки являются обычными. Должны ли быть пустые? – KML

0

Вы упускаете в вас методе возвращения заявления.

Пример с оператором return.

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

    if indexPath.section == 0{ 

     switch (indexPath.row) { 
     case 0: 
      let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! SettingsCell 
     cell.backgroundColor = UIColor.redColor() 
     break 

     case 1: 
      let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! SettingsCell 
     cell.backgroundColor = UIColor.whiteColor() 
     break 

     default: 
      let cellId: NSString = "Cell" 
      var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell 
      break 
     } 
    } 

    if indexPath.section == 1{ 

     switch (indexPath.row) { 
     case 0: 
      let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell10", forIndexPath: indexPath) as! SettingsCell 
     cell.backgroundColor = UIColor.redColor() 
     break 

     case 1: 
      let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell11", forIndexPath: indexPath) as! SettingsCell 
     cell.backgroundColor = UIColor.whiteColor() 
     break 

     default: 
      let cellId: NSString = "Cell" 
      var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell 
      break 

     } 
    } 
    return cell 
} 
+0

, вы возвращаете ячейку за пределами if –

+0

«return cell» дает ошибку «Использование ячейки неразрешенного идентификатора» « – KML

+0

@karlml вам нужно указать ваше имя ячейки таблицы в операторе return ... я думаю, что его SettingsCell .. так напишите эту строку, верните SettingsCell. –

2

Вы должны вернуть ячейку, если раздел номер 2 это методы не будет ничего возвращения, а это тот случай, когда у указать secitons более двух. Решение

  • Второй «если» будет «еще» часть
  • Предельное количество секции
0

вы можете использовать еще, если так:

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

if indexPath.section == 0{ 

    switch (indexPath.row) { 
    case 0: 
     let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! SettingsCell 
    cell.backgroundColor = UIColor.redColor() 
    break 

    case 1: 
     let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! SettingsCell 
    cell.backgroundColor = UIColor.whiteColor() 
    break 

    default: 
     break 
    } 


    else if indexPath.section == 1{ 

    switch (indexPath.row) { 
    case 0: 
     let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell10", forIndexPath: indexPath) as! SettingsCell 
    cell.backgroundColor = UIColor.redColor() 
    break 

    case 1: 
     let cell: SettingsCell! = tableView.dequeueReusableCellWithIdentifier("cell11", forIndexPath: indexPath) as! SettingsCell 
    cell.backgroundColor = UIColor.whiteColor() 
    break 

    default: 
     break 

    } 
} 
return cell 
} 
} 

это может помочь вам попробуйте его

+0

else if indexPath.section == 1 {дает ошибку «Ожидаемое выражение» – KML

+0

ohh !! Не беспокойтесь, проверьте свой код и проверьте выражения. он решит вашу проблему. –

Смежные вопросы