iOS解决cell重用问题

在写sina 微博界面的过程当中使用到了cell,那么就是在cell上添加一些控件,可是因为每条微博的内容都是不一样的,因此在显示的过程当中,出现了内容重叠的问题,其实就是UITableViewCell重用机制的问题。spa

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath .net

code

         static NSString *CellIdentifier = @"Cell"; orm

         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; blog

         if (cell == nil) { rem

          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; get

         } string

              return cell;it

io

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

       static NSString *CellIdentifier = @"Cell";

       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

      if (cell == nil) {

             cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

      }

      return cell;

}

复制代码

TableView的重用机制,为了作到显示和数据分离,IOS tableView的实现而且不是为每一个数据项建立一个tableCell。而是只建立屏幕可显示最大个数的cell,而后重复使用这些cell,对cell作单独的显示配置,来达到既不影响显示效果,又能充分节约内容的目的。

解决方法一:对在cell中添加的控件设置tag的方法

例如在微博内容中须要添加label,那么就能够对添加的label设置tag,而后新建cell的时候先remove前一个cell tag相同的label,再添加新的label,这样就不会出现cell内容的重叠。

[[cell viewWithTag:100] removeFromSuperview];

[[cell contentView] addSubview:contentLabel];

解决方法二:删除cell中的全部子视图

在实现微博界面中,一个cell会有多个控件(label,imageview...),按理说,对每个控件都设置tag,按照第一种解决方法,应该是能够实现的。可是在实际运行过程当中发现不行,仍是会出现内容重叠的问题,因此采用第二种解决方法--在新建cell的时候,若是不是空就删除全部的子视图。

 

     if (cell != nil) { 

        [cell removeFromSuperview];//处理重用 

     } 

解决方法三: 经过为每一个cell指定不一样的重用标识符(reuseIdentifier)来解决。

重用机制是根据相同的标识符来重用cell的,标识符不一样的cell不能彼此重用。因而咱们将每一个cell的标识符都设置为不一样,就能够避免cell重用问题了。


[cpp] view plaincopyprint?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

       NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]];//以indexPath来惟一肯定cell 

       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell 

      if (cell == nil) { 

           cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

      } 

//...其余代码 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

       NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]];//以indexPath来惟一肯定cell

       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell

      if (cell == nil) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

      }

//...其余代码

}

复制代码


原文地址:http://blog.csdn.net/omegayy/article/details/7356823

相关文章
相关标签/搜索