我有一个带有节单元格的表视图控制器,单击它会展开并显示其他子节。一个节单元格将始终具有标题和一个按钮,并且可能具有也可能没有描述,在展开没有描述的单元格时,我在该节单元格的标题上应用了centerYanchor,以便它与展开图标相对应。
在展开具有描述的单元格时,它可以按预期工作,没有描述的部分也对其应用了centerYanchor,并且可以正常工作。
现在我面临的问题是,一旦展开没有说明的单元格,带有说明的单元格在展开时就会开始出现怪异的行为。
如您所见,前两个单元格的说明已正确打开,而其他没有说明的单元格也与按钮对齐。
在这种情况下,我先打开了第三个单元格,然后打开了第一个单元格,即使它已描述了对centerYanchor和hiden逻辑的应用。
这是tableViewController的代码
override func numberOfSections(in tableView: UITableView) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
if tableData[section].opened == true{
return tableData[section].sectionData.count + 1
} else{
return 1
}
}
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "anotherCell",for: indexPath) as? tableCell else {
fatalError("The dequeued cell has thrown some error.")
}
cell.cellTitle.text = tableData[indexPath.section].title
cell.cellDescription.text = tableData[indexPath.section].description
cell.setData = tableData[indexPath.section].opened
return cell
} else{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "subSectionCell",for: indexPath) as? subSectionTableViewCell else {
fatalError("The dequeued cell has thrown some error.")
}
cell.subSectionTitle.text = tableData[indexPath.section].sectionData[indexPath.row - 1]
return cell
}
}
override func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
if tableData[indexPath.section].opened == true {
tableData[indexPath.section].opened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections,with: .none)
}
else{
tableData[indexPath.section].opened = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections,with: .none)
}
}
}
这是用于隐藏centerYanchor并将其应用于单元格的代码
var setData: Bool = false {
didSet{
setupCell()
}
}
func setupCell() {
if (cellDescription.text == "") {
cellDescription.isHidden = true
cellTitle.centerYAnchor.constraint(equalTo: button.centerYAnchor,constant: 4).isactive = true
}
if setData{
button.setImage(UIImage(named: "down"),for: .normal)
} else{
button.setImage(UIImage(named: "right"),for: .normal)
}
}
请向我建议如何解决此问题,如果您有任何疑问,请在评论中提出。
单元格数据结构
struct cData {
var title = String()
var description = String()
var identifier = Int()
var opened = Bool()
var sectionData = [String]()
}
单元格约束