2012-11-01 127 views
14

我有一个UICollectionViewController选择项目以编程方式UICollectionView

- (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负荷,某些项目编程选择,根据他们在CellTasteCollectionViewobjectId

以下是我正在做的:

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

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

当用户点击该项目这就是所谓的 - 这是不是我想要的:我要当UICollectionView负载自动选择的项目。

我该怎么做?

回答

22

我认为你缺少从UICollectionView Class Reference这种方法:

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

,如果你想多选您可以使用此方法多次。

+0

感谢您的帮助。 :) – Ali

+20

请注意,以编程方式调用此方法将不会触发collectionView:didSelectItemAtIndexPath :. – Boon

1

对于连续正确的行为调用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) 
1

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)) 
0
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[self.districtTableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; 
[self tableView:weakSelf.districtTableview didSelectRowAtIndexPath:indexPath]; 

我在tableview中使用上述方法,和它的工作。

相关问题