【发布时间】:2018-02-06 11:40:38
【问题描述】:
我有带有 2 个扩展部分的 UITableView。 所以,当我点击部分的标题时,行将被隐藏:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("Section: \(indexPath.section), Row \(indexPath.row), \(sections[indexPath.section].expanded)")
if sections[indexPath.section].expanded {
return 88
} else {
return 0
}
}
我正在向 UITableView 中的单元格添加 UIlabel,如下所示:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let label = UILabel()
cell.contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
label.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
label.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 30).isActive = true
label.text = "row = \(indexPath.row)"
return cell
}
以上操作正常,但有时单元格无法正确显示屏幕,row1 的内容打印在另一行中。
如果我添加下面的代码,并且当我单击任何部分的标题时,行将正确显示在 tableView 上,但只是一次,我的意思是如果我在标题上再单击一次,则会出现错误发生在 CellForRowAt 函数内部(线程 1:EXC_BAD_ACCESS (code=EXC_I386_GPFLT)):
cell.contentView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
有什么建议吗?
编辑: 只是为了解释这些部分是如何扩展的,我将添加以下内容:
protocol ExpandableHeaderViewDelegate {
func toggleSection(header: ExpandableHeaderView, section: Int)
}
class ExpandableHeaderView: UITableViewHeaderFooterView {
var delegate: ExpandableHeaderViewDelegate?
var section: Int!
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectHeaderAction)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func selectHeaderAction(gestureRecognizer: UITapGestureRecognizer) {
let cell = gestureRecognizer.view as! ExpandableHeaderView
delegate?.toggleSection(header: self, section: cell.section)
}
func toggleSection(header: ExpandableHeaderView, section: Int) {
tableView.beginUpdates()
tableView.endUpdates()
}
}
【问题讨论】:
-
您没有显示所有相关的代码行。
-
请看一下,我包含了所有相关代码。
标签: swift uitableview layer