欢迎使用CSDN-markdown编辑器

来源:互联网 发布:pdf文件朗读软件 编辑:程序博客网 时间:2024/06/07 13:04

最近有人问我关于如何优化TableView,所以特地再次写一篇文章来专门介绍如何优化TableView

1.uitableview的简单认识:
①UITableView最核心的思想就是UITableViewCell的重用机制。
重用机制简单理解就是:UITableView只会创建一屏幕或多一点的UITableViewCell,其他都是从重用池中重用的。每当cell滑出屏幕时,就会把此cell放到一个集合,当要显示某一
个位置的cell时,会先去集合中取,如果有直接拿来用,如果没有,才会创建,这样创建的好处就是,极大的减少了内存的开销。

2.UITableView初级优化:
1)优化探索,项目拿到手时代码是这样:
- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ContacterTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@”ContacterTableCell”];
if (!cell) {
cell = (ContacterTableCell *)[[[NSBundle mainBundle] loadNibNamed:@”ContacterTableCell” owner:self options:nil] lastObject];
}
NSDictionary *dict = self.dataList[indexPath.row];
[cell setContentInfo:dict];
return cell;
}
- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}

2)改进代码后:
- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath {
NSDictionary *dict = self.dataList[indexPath.row];
return [ContacterTableCell cellHeightOfInfo:dict];
}
- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath {
NSDictionary *dict = self.dataList[indexPath.row];
CGRect rect = [dict[@”frame”] CGRectValue];
return rect.frame.height;
}
思路是把赋值和计算布局分离:
但是这样还不是最佳方案,实际上系统都需要调用底层的接口进行绘制,当我们大量添加控件时,对资源的开销也会很大,所以我们可以索性直接绘制,提高效率。

前面那么多,现在写个总结!UITableView的优化主要从三方面入手:
提前计算并缓存好高度
滑动时按需要加载,这个在大量图片展示,网络加载的时候很管用!

除了上面最主要的几个之外,还有很多熟知的优化点:
1.正确使用cell的重用
2.尽量少用或者不用管透明图层
3.如果cell内实现的内容来自web,使用异步加载,缓存请求结果
4.减少subviews的数量
5.在heightForRowAtIndexPath:中尽量不使用cellForRowAtIndexPath:,如果你需要用到它,只用一次然后缓存结果
6.尽量少用addview给cell动态添加View,可以初始化时就添加,然后hide来控制是否显示

0 0
原创粉丝点击