美文网首页开发技术文章iOS
iOS UICollectionView单选和多选

iOS UICollectionView单选和多选

作者: iOSEer冷箭 | 来源:发表于2022-05-09 17:53 被阅读0次

    hello,iOS小伙伴们,上次研究了tableView,这次是UICollectionView,其实和tableVIew 一样的,只是方法不一样啦。我为大家总结了一下,虽然网上都能早到,但是都是零零闪闪的;几行代码搞定UICollectionView 单选和多选:

    1.创建UICollectionView,不用多说了,但是有一个属性很重要 :_collection.allowsMultipleSelection = YES;

    这是单选和多选的关键属性。 YES:是多选。NO或者不写:是单选。

    2.在自定义cell里的方法中判断选中是哪一个图标就OK了。

    -(void)setSelected:(BOOL)selected{

        [supersetSelected:selected];

        if(selected) {

            self.choseBtn.image= [UIImageimageNamed:@"xuan"];

        }else{

            self.choseBtn.image= [UIImageimageNamed:@"no_xuan"];

        }

    }

    3.当你多选取消货选中的时候在方法中移除/添加对应数组的元素就行了。

    -(void)collectionView:(UICollectionView*)collectionViewdidSelectItemAtIndexPath:(NSIndexPath*)indexPath{

        //DF_OpenFileVC *vc = [[DF_OpenFileVC alloc]init];

        //[self pushVC:vc];

        NSLog(@"选中:%ld",indexPath.row);

    }

    -(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{

        NSLog(@"取消选中:%ld",indexPath.row);

    }

    默认第几个选中方法:

    if(indexPath.item==0) {

            //默认第一个选中

            [collectionViewselectItemAtIndexPath:indexPath animated:YES scrollPosition:(UICollectionViewScrollPositionNone)];

        }

    4.全选或者取消全选。is_all:全选标识 1是全选 其他是取消全选;在全选按钮点击事件里对is_all进行赋值,然后刷新UICollectionView

    下面的代码放在:

    -(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

    if ([is_all isEqualToString:@"1"]) {

            [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:(UICollectionViewScrollPositionNone)];

        }else{

            [collectionView deselectItemAtIndexPath:indexPath animated:YES];

        }

    5.全选按钮点击事件:

    if ([is_all isEqualToString:@"1"]) {

            is_all=@"0";

        }else{

            is_all=@"1";

        }

        [self.collection reloadData];

    6.补充一下,tableView 是同理。就能实现全选了。

    相关文章

      网友评论

        本文标题:iOS UICollectionView单选和多选

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