如何交互式地收缩和增长表视图单元格



我在表视图中有一些单元格,用户可以在其中选择"显示更多";并且视图可以展开以显示更详细的信息。相反地,用户可以选择";隐藏";并且视图缩小回其原始大小。

这可能吗?这里是我已经尝试过的扩展功能的简化版本:

UITableViewCell:内部

//MARK: Views
let lbl: UILabel =  {
let lbl = UILabel()
lbl.text = "Initial text."
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.numberOfLines = 0
return lbl
}()
//MARK: Helper functions
func configureViewComponents() {
selectionStyle = .none
addSubview(lbl)
lbl.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0)
}

在我的VC:中配置表格视图

func configureViewComponents() {
view.addSubview(tableView)

tableView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 10, paddingLeft: 0, paddingBottom: 0, paddingRight: 0)
tableView.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true

tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100

tableView.allowsSelection = true
tableView.isUserInteractionEnabled = true


tableView.delegate = self
tableView.dataSource = self


tableView.separatorStyle = .none
tableView.register(EventCell.self, forCellReuseIdentifier: "EventCell")


view.bringSubviewToFront(tableView)
}

委托方法:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
1
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! EventCell
//Do: expand functionality
cell.lbl.text! += " aasdlfkajsdf;lksadj;flaskdfj;alskdjfa;sldkfj;alskdfj;asldkfjas;dlfkasjd;falskdfja;sdlkfajsd;flkasjdfl;askdf;jasldkfajs;dlfjak;sdasdf"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell", for: indexPath) as? EventCell {
return cell
}
return EventCell()
}

我是不是错过了什么?

想明白了。尽管我是以编程方式创建视图的,但您应该将lbl.translatesAutoresizingMaskIntoConstraints设置为TRUE。此外,在展开标签的文本后,调用tableView.reloadData((。

有人理解为什么需要这两个来扩展单元格高度以适应新放大的标签吗?

最新更新