iOS开发文章iOS开发收集iOS开发常见问题

UICollectionView和UITableView的重用问

2016-04-08  本文已影响2883人  随梦而飞飞

情景


collectionView重用出错的效果图

解决方法

具体实现

//初始化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"];
    }
 //把indexPath.row 和 flagArr传进去
       [cell config:indexPath.row andData:self.flagArr];
-(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"];
    }
}
//一答:点击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

上一篇 下一篇

猜你喜欢

热点阅读