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