Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select items programmatically in UICollectionView

I have a 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;
}

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

[self.collectionView setAllowsMultipleSelection:YES];

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

Here's how I'm doing this:

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

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

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.

How do I do this?

like image 883
Ali Avatar asked Nov 01 '12 12:11

Ali


People also ask

How do I select an item in CollectionView programmatically?

collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredVertically];

What is swift Uicollectionview?

An object that manages an ordered collection of data items and presents them using customizable layouts.


1 Answers

I think you are missing this method from the UICollectionView Class Reference:

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

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

like image 154
Masa Avatar answered Sep 21 '22 17:09

Masa