tableview有2个不同的细胞设计

时间:2016-04-14 08:42:45

标签: swift uitableview tableviewcell sections

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

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

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

有可能吗?

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

1 个答案:

答案 0 :(得分:4)

  

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

是的,有可能:)

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

您检查要返回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()
    }
    

希望有所帮助

相关问题