iOS分享的demoiOS 开发~项目常用,经典内容收集首页投稿(暂停使用,暂停投稿)

UITableView的优化

2017-07-19  本文已影响364人  isletn

由于UITableView是日常开发中使用频率相当高的一个视图控件,我们对它用户体验的关注度相比其他视图要高很多。一个顺滑的TableView值得花更多的时间去打磨。

造成卡顿的主要原因
优化方案

@end
3> 在获取model的同时创建对应的MyLayout对象,Model-LayoutObject-Cell一一对应。
NSMutableArray *temp = [NSMutableArray new];
NSMutableArray *temp1 = [NSMutableArray new];
for (NSDictionary *dict in array) {
MyModel *model = [[MyModel alloc] initWithDictionary:dict];
MyLayout *layout = [[MyLayout alloc] initWithMyModel:model];
[temp addObject:model];
[temp1 addObject:layout];
}
self.dataArray = temp.copy;
self.layouts = temp1.copy;
```
3> 通过提取model中的数据确定各个view控件的高度,并提前定义好各个间距的值,通过控件高度与间隔高度求和的方式得到最终的cell高度

 - (void)layoutWithMyModel:(MyModel *)model {
    
    [self layoutMessage:model.message];
    
    CGFloat height = 0;
    height += kTopSpacing;
    height += self.messageH;
    height += kSpacing;
    height += kDefaultTimeHeight;
    height += kSpacing;
    height += kLineHeight;
    self.height = height;
}

4> 实现UITableView的代理,为cell的高度赋值

#pragma mark - UITableView Delegate
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyLayout *layout = self.layouts[indexPath.row];
    return layout.height;
}
思考:创建并将layoutObject存储在self.layouts中,有效的避免了实现动态布局时重复计算cell高度而消耗更多的性能。将这个操作放在后台线程中执行应该对性能的提升更大。

}

3> 在ViewController中创建并使用这个类的实例

self.dataSource = [[MyTableViewDataSource alloc] initWithDataArray:self.dataArray cellReuseIdentifier:kMyCellReuseIdentifier cellConfigureBlock:^(MyTableViewCell *cell, MyModel *item) {
cell.model = item;
}];
self.tableView.dataSource = self.dataSource;


#####PS:以上几点其实都是基于功能模块基本实现并且没有什么问题的情况下做出的优化 ,若你的代码还存在一些基本的问题, 这些优化可能帮不上你什么忙。举个列子:
* 阻塞主线程

#####这种情况UI卡住你就得找找你写的BUG了。
***
####参考资料:
[iOS 保持界面流畅的技巧](http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/)

***
#####最后放上Demo的效果图与地址**[MyTableView](https://github.com/liangzcn/MyTableView)**
![image.png](http:https://img.haomeiwen.com/i2719073/c3039d5303a6b44a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇 下一篇

猜你喜欢

热点阅读