17

我有一个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,允许用户选择多个项目:

[self.collectionView setAllowsMultipleSelection:YES];

我想要的是,第一次加载 CollectionView 时,一些项目会根据它们的objectIdin 以编程方式被选中CellTasteCollectionView

以下是我的做法:

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

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

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

我该怎么做呢?

4

4 回答 4

23

我认为您在UICollectionView 类参考中缺少此方法:

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

如果要进行多项选择,可以多次使用此方法。

于 2012-11-01T13:13:41.757 回答
10

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))
于 2017-10-17T07:02:49.760 回答
2

对于正确的行为,连续调用 4 个函数:

// 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)
于 2017-05-06T04:56:16.067 回答
2
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.districtTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
[self tableView:weakSelf.districtTableview didSelectRowAtIndexPath:indexPath];

我在tableview中使用了上述方法,并且有效。

于 2017-10-17T07:15:35.283 回答