我在表格中制作表单。
假设我有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;
}
加载表视图时,我只想显示第一个单元格,根据答案,将显示不同的单元格。
例如:
可以用 a , b 或 c ,,,,,
firstcell回答
如果我回答 a SecondCell
将显示出答案 x 和 y 。
如果 X 是答案ThirdCell
将显示(除了文本字段,没有选项),并且将显示FourthCell
时
但是如果在FirstCell
中,答案是 b 或 C 只有FourthCell
才会直接显示。
目前我正在通过更改heightForRowAt
中的行高度来进行操作,尽管我认为必须有一种更简单的方法。但是我发现一个问题:
如果我到达ThirdCell
中的Textfield,然后更改我的第一个答案,则SecondCell
是隐藏的,但是ThirdCell
不是,因为它的条件是第二个答案,并且已经做出行作为条件,但我不知道该怎么做。
所以我有两个主要问题:
是否可以访问
heightForRowAt
将其设置为条件?我应该这样做吗?或者,也许有更好的方法来获得我的需求?我阅读了有关将行动态添加和删除到tableViews的信息,但是使用相同的单元格类型,这就是为什么我决定以其高度隐藏它们。
预先感谢!
我认为传统方法是不要修改高度,而是操纵数据源(部分中的行数等)以显示/隐藏适当的单元格。
您应该在事件发生后适当地更新数据源,然后在可以使用func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)
和tableView.deleteRowsAt(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)
之后立即更新数据源。
此文档可能会有所帮助:https://developer.apple.com/documentation/uikit/uitableview/1614879-insertrows
我通常喜欢做的是监视变量,而更新变量时,请调整单元格的高度。确保您的变量已分配给它的Didset代码,以便您的tableView更新变量更改时的高度。
var selectedRow: Int = 999 {
didSet {
tableView.beginUpdates()
tableView.endUpdates()
}
}
然后,就像您已经完成的一样,我会影响高度函数内部的行高度。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == selectedRow { //assign the selected row when touched
let thisCell = tableView.cellForRow(at: indexPath)
if let thisHeight = thisCell?.bounds.height {
print("Bam we got a HEIGHT!!")
return thisHeight + 50
}
}
return 60 //return a default value in case the cell height is not available
}