众所周知,iOS开发中,系统提供了UITableViewCell自动计算高度的机制,但是这个机制性能方面存在问题,因为是实时计算的,拖动的时候TableView实时改变contentSize,表现出来的现象就是拖动的指示器(右边的滑块)会抖动,并且还存在性能问题,达不到顺滑的程度。
最好的办法是在获取到数据的时候就计算出这条数据对应cell的高度。
自动计算高度支持系统autolayout搭建的cell(xib以及snapkit等基于autolayout的约束框架都是支持的)
高度在获取到数据的时候就提前计算出来保存在model里面,实测在iPhone 5s上也能达到60fps的流畅度
效果:
未命名-min (1).gif
Cell布局注意事项:
约束需要能从四个方向撑开cell,这样才能自动算出高度。例如下图:
Screen Shot 2020-04-15 at 6.10.19 PM.jpg
Screen Shot 2020-04-15 at 6.10.19 PM.jpg
实现步骤:
1、搭建cell
我这里是用xib搭建的cell
Screen Shot 2020-04-15 at 10.27.16 PM.png
/// cell即将出现在屏幕中的回调方法 在这个方法里面赋值
func cellWillAppear() {
titleLabel.text = item.feed.title
contentLabel.text = item.feed.content
contentImageView.image = UIImage(named: item.feed.imageName)
usernameLabel.text = item.feed.username
timeLabel.text = item.feed.time
}
3、搭建页面(高度会被自动计算出来)
class AutomaticHeightViewController: UIViewController {
var tableView: UITableView!
var manager: ZJTableViewManager!
var section = ZJTableViewSection()
override func viewDidLoad() {
super.viewDidLoad()
title = "AutomaticHeight"
tableView = UITableView(frame: view.bounds, style: .plain)
view.addSubview(tableView)
manager = ZJTableViewManager(tableView: tableView)
manager.register(AutomaticHeightCell.self, AutomaticHeightCellItem.self)
manager.add(section: section)
// 模拟网络请求
httpRequest(view: view) {
// 网络请求完成
self.showData()
}
}
func showData() {
//获取假数据
let array = getFeedData()
for feed in array {
let item = AutomaticHeightCellItem()
item.feed = feed
//计算高度
item.autoHeight(manager)
//把cell加入进section
section.add(item: item)
}
manager.reload()
}
}
这样就完成了,是不是很简单?
要是有疑惑的话,建议仔细看一下ZJTableViewManager ,里面有demo
码字不易,顺手star是美德:)