collectionView的一些代理方法真的让人😓
抽出实现的主要代码:
/**
只有一组section以 indexpath.row为key,0和1为value标记item是否是选中
*/
@property (nonatomic, strong) NSMutableDictionary *ifSelDic;
//创建collectionview时设置多选
self.collectionView.allowsMultipleSelection = YES;
//部分代理方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
PickCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pickCollecCell" forIndexPath:indexPath];
NSString *title = self.dataSource[indexPath.row];
NSInteger ifSel = [[self.ifSelDic objectForKey:@(indexPath.row)] integerValue];
//cell在这个方法里面设置选中的颜色
[cell setSelected:ifSel title:title];
//这个方法必须实现,而且得在这里实现,他并不是直接设置cell的selected状态的,我感觉他应该是在collectionview系统中做了个标记
[collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
return cell;
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
//called when the user taps on an already-selected item in multi-select mode
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
[self.ifSelDic setObject:@"1" forKey:@(indexPath.row)];
[self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
[self.ifSelDic setObject:@"0" forKey:@(indexPath.row)];
[self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
}
点一下A didSelectItemAtIndexPath会执行,然后刷新,再次点击A didDeselectItemAtIndexPath在执行,然后刷新。。。
而这样玩起来的关键竟然是cell中[collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
有时间再去深究下collection这个select状态怎么标记的呢?路过的也请指教。