解决UITableView上的cell的重用

时间:2023-03-09 15:30:50
解决UITableView上的cell的重用

1.通过为每个cell指定不同的重用标识符(reuseIdentifier)来解决

//        static NSString *rankCellIndefier = @"rankCell";
        NSString *cellMark = [NSString stringWithFormat:@"%ld", indexPath.row];
        
        NewsCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellMark];
        tableView.rowHeight = 80;
        if (cell == nil) {
            cell = [[[NewsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellMark] autorelease];
           if (indexPath.row < 3) {
                  UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
                imageView.tag = 100 + indexPath.row;
                [cell addSubview:imageView];
               [imageView release];
           }
        }
        if (indexPath.row < 3) {
            UIImageView *imageView = (UIImageView *)[cell viewWithTag:100 + indexPath.row];
            imageView.image = [UIImage imageNamed:rankingArray[indexPath.row]];
        }
        cell.titleLabel.text = news.headLineTitle;
        [cell resetLabelFrame:news.headLineTitle];
        cell.dateLabel.text = news.headLineDate;
        cell.rightCountLabel.text = news.headLineCount;
        [pictureAsy pictureCustom:cell imageUrl:news.headLinePhoto indexImage:0];
        return cell;  
    }

删除重用cell的所有子视图

这个方法是通过删除重用的cell的所有子视图,从而得到一个没有特殊格式的cell,供其他cell重用。

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. static NSString *CellIdentifier = @"Cell";
  4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell
  5. if (cell == nil) {
  6. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  7. }
  8. else
  9. {
  10. //删除cell的所有子视图
  11. while ([cell.contentView.subviews lastObject] != nil)
  12. {
  13. [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
  14. }
  15. }
  16. //...其他代码
  17. }