在UICollectionView中以编程方式选择项目

Ali*_*Ali 16 objective-c ios 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;
}
Run Code Online (Sandbox Code Playgroud)

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

[self.collectionView setAllowsMultipleSelection:YES];
Run Code Online (Sandbox Code Playgroud)

我想什么都有,就是第一次的CollectionView负荷,某些项目编程选择的基础上,他们objectIdCellTasteCollectionView.

这是我如何做到这一点:

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

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

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

我该怎么做呢?

Mas*_*asa 23

我认为你从UICollectionView类参考中缺少这个方法:

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,以编程方式调用此方法不会触发collectionView:didSelectItemAtIndexPath:. (22认同)

Bai*_*aig 5

didSelectItemAt如果以selectItem编程方式调用,则不会调用。您应该在该方法之后手动调用该方法。

self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
Run Code Online (Sandbox Code Playgroud)