需求页面大概是这个样子

底部显示的是图片,是动态变化的,文本内容也是动态改变的
实现过程
首先用到了这个代理方法 让cell自适应
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let height = self.heightDic[indexPath] as? NSNumber
if height != nil {
return CGFloat(height!.floatValue)
}else {
return 100
}
}
不设置固定高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
缓存高度
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let height = NSNumber(value: Float(cell.frame.size.height))
self.heightDic[indexPath] = height
}
动态改变的viewframe 需要重新布局 updateConstraints
func configWithModel(_ model: CYListModel, indexRow: Int) {
contentLab.text = model.content
self.showView.removeFromSuperview()
reloadShowView()
if indexRow % 2 == 0 {
self.showView.snp.updateConstraints {
$0.height.equalTo(100)
}
}else {
self.showView.snp.updateConstraints {
$0.height.equalTo(10)
}
}
}
示例:demo
如果出现类似这种 警告
Will attempt to recover by breaking constraint
<SnapKit.LayoutConstraint:0x60c0004a5340@GSDynamicCell.swift#265 UIView:0x7fa5f5eddad0.height == 363.0>
可以尝试给一个priority(100)
imageBgView.snp.makeConstraints {
$0.top.equalTo((weakSelf?.contentLab.snp.bottom)!).offset(16).priority(100)
$0.left.equalTo((weakSelf?.contentLab)!)
$0.height.equalTo(100)
$0.right.equalTo((weakSelf?.contentLab)!)
}
网友评论