Подтвердить что ты не робот

Выбор элементов программно в 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;
}

Это работает. У меня это в viewDidLoad, позволяя пользователю выбирать несколько элементов:

[self.collectionView setAllowsMultipleSelection:YES];

Что я хочу иметь, так это то, что при первом запуске CollectionView некоторые элементы выбираются программно, основываясь на их objectId в CellTasteCollectionView.

Вот как я это делаю:

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

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

Он вызывается, когда пользователь нажимает на элемент - это не то, что я хочу: я хочу, чтобы элемент выбирался автоматически при загрузке UICollectionView.

Как это сделать?

4b9b3361

Ответ 1

Я думаю, что вам не хватает этого метода из Ссылка на класс UICollectionView:

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

Вы можете использовать этот метод несколько раз, если хотите несколько вариантов.

Ответ 2

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))

Ответ 3

Для правильного поведения вызов функции 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)

Ответ 4

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

Я использовал вышеуказанный метод в представлении таблицы, и он работал.