首页 > 解决方案 > 为 UITableView 中的多个单元格提供不同数量的行

问题描述

在此处输入图像描述

你好,我创建了一个UITableView,其中有两个不同的单元格DynamicFormCellStaticFormCell,所以DynamicFormCell可以显示的次数我有来自服务器的数据告诉我需要多少个表格,DynamicFormCell并且StaticFormCell总是相同并且不会改变所以我很难为每个单元格提供不同的行数。我尝试分别给两个单元格 atag01使用以下代码:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(tableView.tag == 0){
            return 5//return five dynamic cells
        }
        if(tableView.tag == 1){
            return 1//return one static cell
        }
    }

但这不起作用,我也尝试删除上面代码中的所有tagsand if statements,只是这样做return 5只给了我一个DynamicFormCell和五个StaticFormCells

我还为两个单元格提供了不同的类,因此我可以分别分配它们:

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

        if(indexPath.row == 0){
            //firstRow make dynamic
            let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicFormsCell") as! DynamicFormsCell
            return cell
        }else{
            //static form data
            let cell = tableView.dequeueReusableCell(withIdentifier: "StaticFormsCell") as! StaticFormsCell
            return cell
        }
    }

所以我的问题是,是否可以使用表格视图来做到这一点,我该怎么做?如果不是,我还有什么其他选择?

标签: iosswiftuitableview

解决方案


您现在正在做的是检查 TableView 的标记是 0 还是 1。这不是您想要做的,因为您只使用一个 TableView。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (amount of DynamicCellsYouWant + amount of StaticCellsYouWant)
}

代码的第二部分仅在您希望第一个单元格为 aDynamicFormsCell而其余为 a时才有效StaticFormsCell


推荐阅读