【问题标题】:cellForRowAt - Create and Return cell from within switch statementcellForRowAt - 从 switch 语句中创建和返回单元格
【发布时间】:2017-07-17 14:52:49
【问题描述】:

我认为我遗漏了 Swift 的一些基本内容,但找不到其他人在做我正在尝试的事情的例子:

背景

我有一个带有 2 个原型单元格的 UITableView,具有不同的标识、不同的功能(标签、图像等)和不同的类。

我希望 cellForRowAt 函数根据包含表数据的数组中的内容返回不同类型和类别的单元格。该数组填充了结构实例,其中一个特征标识了我要表示数据的单元格类型。

代码尝试

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       switch dataArray[indexPath.item].typeOfData {
       case "Type1":
          let cell = tableView.dequeueReusableCell(withIdentifier: "type1ReuseIdentifier", for: indexPath) as! type1Cell
          //Set up the cell contents
          return cell
       case "Type2":
          let cell = tableView.dequeueReusableCell(withIdentifier: "type2ReuseIdentifier", for: indexPath) as! type2Cell
          //Set up the cell contents
          return cell
       default:
          let cell = tableView.dequeueReusableCell(withIdentifier: "separatorIdentifier", for: indexPath) as! separatorCell
          //Set up the cell contents
         cell
     }
}

我错过了什么/做错了什么?


编辑: 它错过了最后的回报。

【问题讨论】:

  • 你写过defaultcase吗?
  • 对不起,是的,默认语句也在那里,并返回一个分隔符类型的单元格
  • “Swift 想让我在 switch 语句之外声明并返回单元格” – 不,我不这么认为。如果 switch 语句中的所有情况都返回一个单元格,那么它应该可以毫无问题地编译。
  • 我是个白痴,你说得对,马丁,我的一个开关盒没有返回!

标签: ios swift uitableview


【解决方案1】:

就这样吧:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let typeSection = CellType(rawValue: indexPath.row)!

    switch typeSection {
    case .CenterTitleCell:
        return getCenterTitleCell(tableView, indexPath)
    case .CenterDescriptionCell:
        return getCenterDescriptionCell(tableView, indexPath)
    case .CenterImageCell:
        return getImageCell(tableView, indexPath)
    case .FooterTitleCell:
        return getFooterViewCell(tableView, indexPath)
    }
}

并使用另一种方法返回单元格类型

func getCenterTitleCell (_ tableView: UITableView, _ indexPath:IndexPath) -> CenterTitleTableViewCell {
    let cell:CenterTitleTableViewCell =  tableView.dequeueReusableCell(withIdentifier: String(describing: CenterTitleTableViewCell.self),
                                                                                   for: indexPath) as! CenterTitleTableViewCell
    cell.selectionStyle = .none
    return cell
}

【讨论】:

  • 假设只有 4 行,每行都有自己的单元格类型。一般来说,这不是大多数表的设置方式。
  • 这是一个简单的例子。在这种情况下,我有一个提供单元格类型的枚举,因为它是一个静态屏幕。应该使示例适应他想要的代码。
猜你喜欢
  • 2021-07-26
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
相关资源
最近更新 更多