UICollectionView和UITableView的重用问

作者: 随梦而飞飞 | 来源:发表于2016-04-08 00:54 被阅读2883次

情景

  • 今天我在做一个相册选择问题中,发现当点击第一个cell时cell中but的图片发生改变了但是继续往下滑的时候就出现了问题我只点击了一个但是 下面的cell的中btn的图片也改变了~

collectionView重用出错的效果图
  • 没有点击下面的但是 还是被勾选了 collectionView的重用出现了问题

解决方法

  • 使用一个数组 flagArr 存储所有cell的状态
  • 把indexPath.row 和这个数组flagArr 传入cell中 然后进行赋值
  • 根据点击的cell 进行判断然后给flagArr数组进行数据的更新

具体实现

  • -> viewDidLoad中
//初始化flagArr
    self.flagArr=[NSMutableArrayarray]; 
   //初始化数据源    self.dataArr=[NSMutableArrayarray];   
  for (int i=0; i<80; i++) {       
  [self.dataArraddObject:[NSStringstringWithFormat:@"%d",i]];      
  //把flagArr 的个数和数据源的个数设置成相同的      
  //而且用0初始化~也就是一开始 cell的状态全都是未选中        
    [self.flagArraddObject:@"0"];
    }
  • -> cellForRow或者cellForItem中 (第三问)
 //把indexPath.row 和 flagArr传进去
       [cell config:indexPath.row andData:self.flagArr];
  • ->cell中
-(void)config:(NSInteger)index andData:(NSMutableArray*)flagArr;
{   
 //给需要点击cell改变的状态的控件设置tag    
//为了能在外面取到  然后通过点击cell给控件改变状态和属性    
self.selectImageView.tag=8888+index;    
//赋值判断:如果在index位置的值为0  就是未被选中  1就是被选中  
  if ([flagArr[index] intValue]){     
   self.selectImageView.image=[UIImageimageNamed:@"FriendsSendsPicturesSelectBigYIcon"];   
 }else {        
  self.selectImageView.image=[UIImageimageNamed:@"FriendsSendsPicturesSelectBigNIcon"];
    }
}
  • ->控制器的 didSelected 点击cell的方法中
//一答:点击item响应的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{   
 //这个是关键通过indexPath 拿到这个cell 这个方法我老师忘记    
UICollectionViewCell * cell =[collectionView cellForItemAtIndexPath:indexPath];  
  //拿到这个cell中的控件   
 UIImageView * selICon=(UIImageView *)[cell viewWithTag:8888+indexPath.row];   
 //通过indexPath。row 取到这个cell的状态 0就是未被选中,1就是已经被选中了   
 int cellFlag=[[self.flagArrobjectAtIndex:indexPath.row] intValue];    
if (cellFlag) {        
[self.flagArrsetObject:@"0"atIndexedSubscript:indexPath.row];        
selICon.image=[UIImageimageNamed:@"FriendsSendsPicturesSelectBigNIcon"];    
}else {   
    [self.flagArrsetObject:@"1"atIndexedSubscript:indexPath.row];        
selICon.image=[UIImageimageNamed:@"FriendsSendsPicturesSelectBigYIcon"];  
  }
}

现在你在运行的话UICollectionView或者UITableView的重用问题就解决了哦~~

参考Demo:GitHub

相关文章

网友评论

  • 松果der:其实呢就是每次重用的时候根据indexPath锁定cell配置特定的cell,不然就会出现你那种情况,相当于只配置了5个或6个cell
    苜蓿鬼仙:@松果der 同求怎么解决这种重用问题呀?
    随梦而飞飞:@松果der 大神 不知道 怎么弄 求告知 谢谢
  • 鼻毛长长:cell configureWithModel
    随梦而飞飞:@鼻毛长长 我这里只是演示重用的问题~~没有更新cell中的数据~~如果你要更新数据的话~~可以在 [cell config:indexPath.row andData:self.flagArr]; 方法中在 传入一个~数据源~~ cell中可以 通过 数据源和index 拿到 model~然后在设置 就好了
  • 鼻毛长长:每次重用的时候都配置一下cell

本文标题:UICollectionView和UITableView的重用问

本文链接:https://www.haomeiwen.com/subject/utlvlttx.html