TableView和性能优化

一:UITableView
1、UITableViewController继承于UIViewController,内部的tableView就是控制器的self.view
2、UITableView的性能优化:
1)、每当一个cell进入视野范围内就会调用一次-cellForRowAtIndexPath:这个方法,在这个方法里就会创建一个新的cell,这样在滚动tableView时就会不断的创建新的cell增加内存开销,要进一步优化。
优化思路:
搞一个缓存池,把tableview可视范围内已经创建的cell放在缓存池,当再次滚动tableView时在可视范围内重新出现的cell,先去缓存池中找看有没有可用的cell,如果没有的话再创建cell。离开屏幕的cell如果不放在缓存池会被销毁。

注意: static NSString *identifier = @"cell";静态局部变量在只占一份内存,但不会改变作用域。
利用注册方法创建cell
注册方法特点:只能注册一次,并且在缓存池循环利用之前,也不能确定cell样式。
例如:想显示cell.detailLabel都显示不了。

3、UITableView的索引条
当滚动的时候上面的



4、字典转模型框架

5、用代码创建cell或通过xib方法自定义cell
该方法根据先从缓存池取相应的cell,取不到的话通过判断不存在就创建cell



注意:如果bundle为nil 就默认为mainBundle,cell的高度是由tableview的rowHeight属性或代理方法决定的,在xib中设置cell的高度是无效的,默认44
6、通过storyboard直接在控制器中自定义cell
在拖动tableViewCell时候tableView的rowHeight会跟随改变,所以我们不要在用代码设置tableView的rowHeight或通过代理方法设置.


7、自定义分割线
自定义分割线
8、自定义不等高cell
- 纯代码方式:
-
frame:
image.png
-
-
设计思路:
1.在模型中分别新增保存每个控件frame的属性
2.在模型中新增一个cellHeight属性,然后在get方法中根据设置每个控件的frame并赋值给相对于的模型属性,然后计算cell的高度。
3.在cell的 layoutSubViews 方法中 把模型中的保存的每个控件的frame赋值给控件
4.在设置cell高度的 heightForRowAtIndexPath:方法中根据indexPath拿到对应的模型,然后通过getter方法获取cell高度。即是模型中getter方法,为了提高性能,要判断模型中的cellHeight是否有值,没值的话再算。相应的代码如下:
image.png



- storyboard方式:
- 核心代码





注意:
如果tableviewcell是从storyboard或xib加载的,不会调用 initWithStyle: reuseIdentifier:方法,会调用 awakeFromNib方法进行初始化。
9、 tableView的全局和局部刷新
- 全局刷新:
reloadData方法 - 1.局部刷新:
reloadRowsAtIndexPaths: withRowAnimation:这种方法适合于cell的个数不变化的刷新。 - 2.增加cell的刷新:
insertRowsAtIndexPaths: withRowAnimation: - 3.删除cell的刷新:
deleteRowsAtIndexPaths: withRowAnimation:



刷新会重新调用数据源方法。
10、左滑删除功能
-
左滑删除功能
image.png
-
左滑cell出现多个按钮
image.png

-
批量删除
1.要进入编辑模式:默认情况下左边会出现一排红色的“减号”按钮,点击减号按钮相当于左滑。
self.tableView.editing = yes;
或 [self.tableView setEditing: animation:];
2.设置编辑模式下可以多选:
self.tableView.allowsMultipSelectionDurtingEditing = yes;


-
自定义批量删除cell
思路:改变cell子控件是否显示不能通过拿到cell来操作,因为从缓存池取cell时候可能出现错乱,要通过模型决定cell子控件界面的显示。
自定义批量删除cell

