【问题标题】:tableview with 2 sections different design for cells具有 2 个部分的表格视图,用于单元格的不同设计
【发布时间】:2016-04-14 08:42:45
【问题描述】:

我需要 2 在同一个屏幕中有 2 个表格(每个表格的单元格设计不同)。

我不确定我是否应该在同一个视图中使用 2 个表格(滚动现在搞砸了),或者有一个包含 2 个部分的表格并在每个部分中设计不同的单元格。

我还没有找到任何包含 2 个部分的表格视图的示例,以及 2 个部分中单元格的不同设计。

有可能吗?

或者我应该尝试使用 2 个不同的表来解决吗?

【问题讨论】:

    标签: swift uitableview tableviewcell sections


    【解决方案1】:

    我还没有找到任何示例,其中包含 2 个部分的表格视图和 2 个部分中的不同单元格设计。有可能吗?

    是的,有可能:)

    这是您使用UITableViewDataSource 协议中的tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 方法的地方。

    您检查要为哪个部分返回UITableViewCell 的子类,创建一个实例,也许填充它,然后返回它。

    所以你需要这样做。

    • 使用 NIB 文件创建 UITableViewCell 的多个子类。
    • 例如,在viewDidLoad() 中,您可以像这样注册 NIB:

      tableView.registerNib(UINib(nibName: "Cell1", bundle: nil), forCellReuseIdentifier: "Cell1")
      tableView.registerNib(UINib(nibName: "Cell2", bundle: nil), forCellReuseIdentifier: "Cell2")
      
    • tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) 中,您检查要求哪个部分并返回正确的子类(有改进的空间:-)):

      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          switch indexPath.section {
          case 0:
              if let cell1 = tableView.dequeueReusableCellWithIdentifier("Cell1") as? Cell1 {
                  //populate your cell here
                  return cell1
              }
          case 1:
              if let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2") as? Cell2 {
                  //populate your cell here
                  return cell2
              }
          default:
              return UITableViewCell()
          }
          return UITableViewCell()
      }
      

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多