UICollectionView多选

multi.gif

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状态怎么标记的呢?路过的也请指教。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • UICollectionView默认不会进行选中和高亮,想实现这种效果只需要设置allowsMultipleSel...
    loyt阅读 856评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,593评论 25 709
  • 初级魔宝学后感! 转眼四十二天的魔宝初级学习结束了!既兴奋又有几分失落! 这四十二天对于我来说是煎熬...
    冒冒泡小鱼阅读 353评论 6 2
  • 足球场上的两只兔子 一只灰色,一只黑色 相约在雨后的红豆树下 妄想搭乘七色虹桥,回归至广寒宫 仰望蓝天,或者想象从...
    羊高士阅读 130评论 0 0
  • 背井离乡去打工 风餐露宿腹中空 辛劳节俭为何事 明年高考鲤化龙
    一叶茶阅读 116评论 0 3