UITavleView自定义Cell和重用机制常见错误分析
来源:互联网 发布:什么是网络通信软件 编辑:程序博客网 时间:2024/05/17 06:57
系统的Cell提供了几种样式,但是在一些情况下,依然需要自定义cell才能满足业务需求。当同时采用自定义cell和cell重用机制的时候,容易出现以下两种问题。
先来看第一种错误代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *indentifier = @"cell"; OrderItemViewCell *cell = (OrderItemViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier]; if (!cell) { cell = [[OrderItemViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier]; Order *order = [ordersArray objectAtIndex:indexPath.row]; //填充cell的内容 [cell setContentWithOrder:order]; } return cell;}
错误原因:cell只有在没有被创建的时候才会执行if代码块中的内容,这意味着cell只会在初始化的时候更新一次。
错误表现:只有少数几个cell不断重复,在下拉过程中出现与之前相同的cell。再次返回顶部,cell的内容也会改变。
以下是第二种常见错误代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *indentifier = @"cell"; OrderItemViewCell *cell = (OrderItemViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier]; if (!cell) { cell = [[OrderItemViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier]; } Order *order = [ordersArray objectAtIndex:indexPath.row]; //填充cell的内容 //setContentWithOrder方法中通过新增addSubview 的方式新增UI控件 [cell setContentWithOrder:order]; return cell;}
错误原因:cell每次出现的时候都会触发cellForRowAtIndexPath方法,这意味着cell每次出现都会新增一些UI控件。
正确解决方式:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *indentifier = @"cell"; OrderItemViewCell *cell = (OrderItemViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier]; if (!cell) { cell = [[OrderItemViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier]; } Order *order = [ordersArray objectAtIndex:indexPath.row]; //填充cell的内容 //setContentWithOrder方法中更改UI控件内容 [cell setContentWithOrder:order]; return cell;}
总结:
1.cell不在屏幕范围内时,被加入重用队列,新出现的cell将从重用队列中选择,所以一个表格中可能有若干个cell显示内容不同,但是cell指针指向的地址完全相同。
2.cell的初始化方法,只调用一次,而cellForRowAtIndexPath会在一个cell即将出现的时候被调用,可能会被调用无限次。
3.因此,if代码块中写上cell的初始化方法,同时只应该涉及到UI控件的创建和静态内容的赋值。
4.if代码块外,动态更新cell的UI控件内容。
0 0
- UITavleView自定义Cell和重用机制常见错误分析
- 用storyboard和Xib自定义cell常见错误
- cell重用机制理解
- Cell的重用机制
- cell的重用机制
- cell重用机制
- cell重用机制
- cell的重用机制
- cell的重用机制
- 自定义UITableViewCell重用cell
- 关于uitableview自定义cell与重用机制探究
- (iphone/ipad)关于uitableview自定义cell与重用机制探究
- xib,story中自定义cell重用机制的一些疑问
- IOS Table中Cell的重用reuse机制分析
- IOS TableView中Cell的重用reuse机制分析
- IOS Table中Cell的重用reuse机制分析
- IOS Table中Cell的重用reuse机制分析
- IOS Table中Cell的重用reuse机制分析
- JSP动态网页技术基本知识点总结
- Java中有关Null的9件事
- 安装genymotion是出现unable load virtualbox engine错误的原因
- tomcat 配置访问路径为/
- java.lang.IllegalArgumentException: Document base问题报异常
- UITavleView自定义Cell和重用机制常见错误分析
- 类和对象:数据成员之使用默认参数初始化
- 【BZOJ3211】花神游历各国 树状数组 并查集 均摊分析
- 《C++编程》第二章第10题
- 函数间的参数传递
- (7.2.1)SQL之基础笔试题
- 也来一个高大上的界面
- 通过Java模拟各种类型的耦合
- 机器学习实战-Logistic回归