Clash Royale CLAN TAG#URR8PPP
How do I return back to the first collectionview cell item?
I'm working in CollectionView Cells for my mobile app. When you tap the 'crossBtn' it goes back to the first collectionview cell with reloading the data but because it has done 'collectionView?.reloadData()' the colours are messed up and it doesn't stay to one colour at a time per cell, instead it keeps selecting multiple colours on the cells even though I've put the colour as 'clear' in 'didDeselectItemAt'.
How do I return back to the first collectionview cell item when the user taps on 'crossBtn' without reloading the data?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filters.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.hamburgerLabel.text = filters[indexPath.item]
// cell.hamburgerImageView.image = filterImages[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.backgroundColor = UIColor.gray.cgColor
setFilter(title: filterNames[indexPath.row])
toolBar.isHidden = true
yesAndNoToolBar.isHidden = false
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.backgroundColor = UIColor.clear.cgColor
collectionView.deselectItem(at: indexPath, animated: true)
}
@IBAction func crossBtn(_ sender: UIBarButtonItem) {
toolBar.isHidden = false
yesAndNoToolBar.isHidden = true
collectionView?.reloadData()
let indexPath = self.collectionView.indexPathsForSelectedItems?.last ?? IndexPath(item: 0, section: 0)
self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.centeredVertically)
}
scrollToItem(at:at:animated:)
1 Answer
1
You may not have to reload the data. You can use the following method to scroll to a given index path.
let indexPath = self.collectionView.indexPathsForSelectedItems?.last ?? IndexPath(item: 0, section: 0)
func scrollToItem(at indexPath: indexPath,
at scrollPosition: .centeredVertically,
animated: true)
Note that this is different from using selectItem(at:animated:scrollPosition:)
.
selectItem(at:animated:scrollPosition:)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use
scrollToItem(at:at:animated:)
to scroll to the first index path– particleman
30 mins ago