2012-11-01 12 views
14

Mam UICollectionViewController:Wybierz elementy programowo w 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; 
} 

To działa. Mam to w viewDidLoad, pozwalając użytkownikowi wybrać kilka pozycji:

[self.collectionView setAllowsMultipleSelection:YES]; 

Co chcę mieć, jest to, że po raz pierwszy ładuje CollectionView, niektóre elementy się wybrany programowo, w oparciu o ich objectId w CellTasteCollectionView.

Oto jak to robię:

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

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

Nazywa się, gdy użytkownik kliknie na przedmiocie - to nie jest to, co chcę: Chcę element, który ma zostać wybrany automatycznie, gdy UICollectionView ładunki.

Jak to zrobić?

Odpowiedz

22

myślę, że brakuje tej metody z UICollectionView Class Reference:

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

Można użyć tej metody wiele razy, jeśli chcesz wybrać więcej.

+0

Dzięki za pomoc. :) – Ali

+20

Należy pamiętać, że wywołanie tej metody programowo nie uruchomi metody collectionView: didSelectItemAtIndexPath :. – Boon

1

Na prawo zachowania wezwanie 4 funkcje w jednym rzędzie:

// 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 nie nazywa jeśli zadzwonisz selectItem programowo. Należy wywołać metodę ręcznie po tym.

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]; 

, że stosuje się wyżej opisany sposób w tableview i pracował.

Powiązane problemy