我正在表格 View 中制作表格。
假设我有 4 种不同类型的细胞,每一种都是一个具有不同类型答案的问题
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if sortedFixedContentType.count != 0 {
let item = sortedFixedContentType[indexPath.row]
switch item.typeId {
case "1":
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! FirstCell
return cell;
case "2":
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) as! SecondCell
cell.customDelegate = self
return cell;
case "3":
let cell = tableView.dequeueReusableCell(withIdentifier: "ThirdCell", for: indexPath) as! ThirdCell
cell.commentsTextView.delegate = self
return cell;
case "4":
let cell = tableView.dequeueReusableCell(withIdentifier: "FourthCell", for: indexPath) as! FourthCell
return cell;
}
当加载 tableView 时,我只想显示第一个单元格,并且会根据答案显示不同的单元格。
例如:
FirstCell 可以用A、B 或C 来回答,
如果我回答 A SecondCell
将显示答案 X 和 Y。
如果 X 是答案,将显示 ThirdCell
(除了 TextField 没有其他选项),完成后将显示 FourthCell
但是如果在FirstCell
中答案是B或C只有FourthCell
将直接显示。
目前我是通过更改 heightForRowAt
中行的高度来实现的,尽管我认为一定有更简单的方法。
但是我发现了一个问题:
如果我到达 ThirdCell
中的 textField,然后更改我的第一个答案,SecondCell
被隐藏,但 ThirdCell
不是,因为它的条件是第二个答案,它已经做出来了,所以我想将每行的高度设置为条件,但我不知道该怎么做。
所以我有两个主要问题:
是否可以访问
heightForRowAt
以将其设置为条件?我应该这样做吗?或者也许有更好的方法来获得我需要的东西?我阅读了有关在 TableView 中动态添加和删除行但单元格类型相同的信息,这就是为什么我决定改为按高度隐藏它们的原因。
提前致谢!
最佳答案
我认为传统的方法是不修改高度,而是操作数据源(节中的行数等)来显示/隐藏适当的单元格。
您应该在事件发生后适本地更新数据源,然后在可以使用 func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)
和 tableView 后立即更新数据源。 deleteRowsAt(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)
在 tableView 中插入/删除单元格
此文档可能会有所帮助:https://developer.apple.com/documentation/uikit/uitableview/1614879-insertrows
关于ios - 有条件地更改 UITableView 中单元格的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266955/