Select items programmatically in UICollectionView

2020-02-05 02:27发布

问题:

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?

回答1:

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.



回答2:

didSelectItemAt is not called if you call selectItem programmatically. You should call the method manually after it.

self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))


回答3:

For right behaviour call 4 function in a row:

// Deselect
self.collection.deselectItem(at: previousPath, animated: true)
self.collectionView(self.collection, didDeselectItemAt: previousPath)

// Select
self.collection.selectItem(at: path, animated: true, scrollPosition: .centeredVertically)
self.collectionView(self.collection, didSelectItemAt: path)


回答4:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.districtTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
[self tableView:weakSelf.districtTableview didSelectRowAtIndexPath:indexPath];

I used the above method in tableview, and it worked.