在 UICollectionView 中以编程方式选择项目 [英] Select items programmatically in UICollectionView

查看:16
本文介绍了在 UICollectionView 中以编程方式选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UICollectionViewController:

- (NSInteger)collectionView:(UICollectionView *)collectionView 
     numberOfItemsInSection:(NSInteger)section {
    return [self.pageTastes count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView  
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     CellTasteCollectionView *cell = 
       [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" 
                                                 forIndexPath:indexPath];
     Taste *taste = [self.pageTastes objectAtIndex:indexPath.item];       
     [[cell imageView] setImage:taste.image];
     [cell setObjectId:taste.objectId];    
     return cell;
}

它有效.我在 viewDidLoad 中有这个,允许用户选择多个项目:

It works. I have this in viewDidLoad, allowing the user to choose multiple items:

[self.collectionView setAllowsMultipleSelection:YES];

我想要的是,CollectionView 第一次加载时,根据 CellTasteCollectionView 中的 objectId 以编程方式选择一些项目.

What I want to have, is that the first time the CollectionView loads, some items get selected programmatically, based on their objectId in CellTasteCollectionView.

我是这样做的:

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

    Taste *taste = [self.pageTastes objectAtIndex:indexPath.item];
    printf("%s
", [taste.objectId UTF8String]);
}

当用户点击项目时调用它——这不是我想要的:我希望在 UICollectionView 加载时自动选择项目.

It's called when the user clicks on the item -- this is not what I want: I want the item to be selected automatically when UICollectionView loads.

我该怎么做?

推荐答案

我认为您在 UICollectionView 类参考:

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition

如果要多选,可以多次使用此方法.

You can use this method multiple times if you want multiple selections.

这篇关于在 UICollectionView 中以编程方式选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆