Reputation: 71
I want to highlight the specific cell of the UICollectionView by default.
However I can not do that.The code is below.
UIView(in the init method):
let selectedIndexPath = IndexPath(item: 0, section: 0)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: [])
UICollectionViewCell:
override var isSelected: Bool {
didSet {
imageView.tintColor = isSelected ? UIColor.white : UIColor.red
}
}
How can I select specific indexpath of a UICollectionView by default ? If you need any other information to solve it, let me know. Thank you.
Upvotes: 1
Views: 3607
Reputation: 71
This only selects the first cell
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//add here
let selectedIndexPath = IndexPath(item: 0, section: 0)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: [])
}
Upvotes: 2
Reputation: 1196
You should override this method
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//you should set needed cells as selected here, or set it to deselected, because it is your responsibility now
var shouldSelect = false //or true
cell.isSelected = shouldSelect
}
But in this case you should keep track of collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) method and reload collection while selection.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.reloadData()
//or reload sections
}
Upvotes: 0