我正在尝试使用以下代码创建可扩展的uitaiteViewCells:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = tableView.cellForRow(at: indexPath) as! feedBaseCell
if cell.expandButton.isExpanded == true {
return 128
} else {
return 64
}
return 64
}
.isExpanded
是feedbasecell的自定义属性。当我运行此代码时,LINE let cell = tableView.cellForRow(at: indexPath) as! feedBaseCell
会遇到EXC_BAD_ACCESS错误。如何检查.isExpanded
属性并根据该属性返回高度是对还是错误?为什么我的代码不起作用?
编辑:cellForRowAt
和numberOfRowsInSection
的代码:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "feedBaseCell") as! feedBaseCell
cell.backgroundColor = .clear
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.contentView.isUserInteractionEnabled = false
cell.expandButton.tag = indexPath.row
cell.expandButton.addTarget(self, action: #selector(self.expandTheCell(_:)), for: .touchUpInside)
cell.contentView.bringSubview(toFront: cell.expandButton)
return cell
}
这是expandTheCell
方法:
func expandTheCell(_ sender: UIButton) {
if sender.isExpanded == false {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
sender.transform = sender.transform.rotated(by: .pi/2)
sender.isExpanded = true
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
sender.transform = sender.transform.rotated(by: -.pi/2)
sender.isExpanded = false
}, completion: nil)
}
tableView.beginUpdates()
tableView.endUpdates()
}
切勿从heightForRowAt
中调用cellForRow(at:)
。它会导致无限的递归,因为当您要求使用该单元时,表视图试图获得单元的高度。
如果您真的需要获取一个单元格来计算其高度,请直接调用视图控制器的数据源方法tableView(_:cellForRowAt:)
方法而不是表视图的cellForRow(at:)
方法。
但是在这种情况下,您不需要单元格。您应该将每行扩展的状态存储在数据源数据中,而不是在单元格本身中。查看该数据,而不是单元格,以确定heightForRowAt
方法的高度。当然,您将需要cellForRowAt
数据源方法中的此状态信息,因此您可以在此处设置单元格的状态,因为在滚动表视图时会重新使用。