IOS: viewing a collection, selectItemAtIndexPath does not work programmatically

I do not know why this does not work. indexOfIcon is correct, the section is correct (marked in NSLog) If I select one, everything will be correct. But this line does nothing ... why? If selected, it should have a blue frame. This works great by doing it "manually", but not with code.

- (void)viewWillAppear:(BOOL)animated
{
    NSUInteger indexOfIcon;
    if(self.mainCategory.icon){
        indexOfIcon = [self.icons indexOfObject: self.mainCategory.icon];
    } else {
        indexOfIcon = 0;
    }
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
}
+4
source share
2 answers

add

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.selected = YES;

and the cell will be selected.

The command [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];tells collectionView that the cell is in the selected state, but does not set the state of the cell.

+9
source

After choosing years, it seems to work fine (even in viewDidLoad :)

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[_collection selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionLeft];

successfully starts cell -setSelected:

0

All Articles