pre select/highlight UICollectionViewCell on first load of view
In viewDidAppear
:
NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection:0];
[self.dateCollectionView selectItemAtIndexPath:indexPathForFirstRow animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.dateCollectionView didSelectItemAtIndexPath:indexPathForFirstRow];
For swift 3
Use collectionView.selectItem
with-in this overload collectionView(UICollectionView, IndexPath)
This is my code, in this code I pre selected row with indexPath.row = 0
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = ScenarioCollectionView.dequeueReusableCell(withReuseIdentifier: "ReuseScenarioCollectionViewCell", for: indexPath as IndexPath) as! ScenarioCollectionViewCell
if (indexPath.row == 0){
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
cell.layer.borderColor=UIColor.gray.cgColor
}else{
cell.layer.borderColor=UIColor.white.cgColor
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderColor = UIColor.gray.cgColor
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath as IndexPath)
cell?.layer.borderColor = UIColor.white.cgColor
collectionView.deselectItem(at: indexPath, animated: true)
}
For Swift 3.0.1 You can try this:
self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
or
self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))
For Objective-C You can try this:
self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
Note: You should use it in viewDidAppear