ios - 为 UITableView 中的多个单元格提供不同的行数

标签 ios swift uitableview

enter image description here

你好, 我创建了一个 UITableView,其中有两个不同的单元格 DynamicFormCell 和 StaticFormCell,因此可以显示 DynamicFormCell我从服务器获得的数据告诉我 DynamicFormCell 需要多少个表单,而 StaticFormCell 始终相同并且不会改变,所以我有多少次为每个单元格提供不同的行数很困难。我尝试分别为两个单元格提供 01tag 并使用以下代码:

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
        }
    }

但这不起作用,我还尝试删除上面代码中的所有标签if语句,然后执行此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
        }
    }

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

最佳答案

是的,单个表格 View 中可以有多种类型的单元格。与功能无关

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

您应该将单元格返回为,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 return (count of dynamic cells + count of static cells)
}

我假设,您只需在底部显示静态单元格。因此,如果总共有 5 个单元格,那么 4 个单元格是动态的,第 5 个单元格是静态的。

因此,cellForRowAt indexPath: 的代码将是,

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

        if(indexPath.row < (count for dynamic cells)){
            //first 4 Rows make dynamic
            let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicFormsCell") as! DynamicFormsCell
            return cell
        }else{
            //last row static form data
            let cell = tableView.dequeueReusableCell(withIdentifier: "StaticFormsCell") as! StaticFormsCell
            return cell
        }
    }

关于ios - 为 UITableView 中的多个单元格提供不同的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57693783/

相关文章:

IOS:如何将 NSArray 转换为 NSIndexPath

ios - 将 UIView 移动到新的 super View 并从 UITableViewCell 返回

swift - 快速在 UITableView 中创建下拉菜单

ios - 跟踪 MKMapView 旋转

swift - 如何创建一个函数来返回两个不同数组中的值的匹配项?

ios - 导航标题 UIImageView 无法居中

json - 将 json 集合响应映射到 swift 对象类的简单方法

ios - 如何从 twitter api 的结果中获取具体细节?

ios - 如何更改 UIGraphicsGetCurrentContext 的 fillColor?

ios - FIRDatabaseReference 返回 nil,但可检索 UserID