i was trying to create a collection view with a list of cells. And when user hits a button it will random select one of the cell.
Now suppose there are only 10 cells. i.e numberOfItemsInSection
delegate return 10.
The view controller is the data source for the collectionView. The collection view is called myCollectionView
. And it has a property called selectedIndexPath
So ViewController:
@interface ViewController () < UICollectionViewDataSource>
@property (nonatomic, strong) NSIndexPath * selectedIndexPath;
@property (strong, nonatomic) IBOutlet UICollectionView *myCollectionView;
@end
Here's my random select code in the view controller:
-(void)chooseRandom{
NSInteger randomShadeIndex = arc4random_uniform((uint32_t)10);
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:randomShadeIndex inSection:0];
self.selectedIndexPath = indexPath;
[self.myCollectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
}
And here's my cellForItemAtIndexPath
in my view controller
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MyCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.selected = self.selectedIndexPath == indexPath;
return cell;
}
And here's setSelected:
method in MyCell
:
- (void)setSelected:(BOOL)selected{
[super setSelected:selected];
if (selected){
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor greenColor];
}
}
So now when i call chooseRandom
from the button press. If the random cell to be selected is not visible(not in current screen), then there's a high chance that it doesn't end up having setSelected:YES
called during the selectItemAtIndexPath:
.(Or it gets called but sets the cell.selected to NO
instead of YES
). Meaning the resulting screen has none of the cell selected.
And the interesting thing is, when i tried touching the screen (without selecting any cell). It will called the setSelected:
on the cell to be selected. So i think selectItemAtIndexPath:
is bugged.
And this only happens, when prefetching enabled
in interface builder is set to be enabled.(which is the default for ios 10).
And i've tried following ways to solve this, but none of them works:
Add
[self.myCollectionView cellForItemAtIndexPath:indexPath].selected = YES;
at the end ofchooseRandom
.Use
scrollToItemAtIndexPath
along with method 1 instead ofselectItemAtIndexPath:
I think either this is a bug or I ignore something completely. I've been stuck on this for hours and couldn't figure out why. Now i think it is most likely a bug for selectItemAtIndexPath
with prefetching enabled
is set.
Please help me and tell me if you encounter the same issue. Thanks!
EDIT: not sure if the same question. this link has similar issue but with deselect