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