简体   繁体   中英

ScrollToItemAt in UICollectionView does not work

I create a horizontal menu using the UICollectionView in Storyboard (Swift). There was a problem when scrolling the collection to the active cell - the scrolling works correctly only without updating the collection. And I need to update it in order to display an active cell (text color and line at the bottom, which are hidden in a non-active cell). The essence of the problem is clearly visible in the animations that are attached to the code.

How can I correct the problem and make a truly worker menu?

CODE 1 scroll is correct, cells is not reload gif-demonstration

//1
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  collectionMenu.isPagingEnabled = false
  collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
  collectionMenu.isPagingEnabled = true

}

CODE 2 cells reloaded, but scroll is broken gif-demonstration

//2
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  collectionMenu.reloadData() //change design active cell
  collectionMenu.isPagingEnabled = false
    collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
    view.layoutIfNeeded()
    collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
  collectionMenu.isPagingEnabled = true

}

Rather than reloading the collectionView on didSelectItem(at:) you'll want to update the cell styling manually from there. I don't think there's also any need to toggle paging on the collectionView on and off from didSelect either.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)

    guard let cell = collectionView.cellForItem(at: indexPath) as? YourCell else { return }
    cell.titleLabel.text = // Your orange colour
}

You may also need to override the prepareForReuse method inside your cell like so to prevent dequeuing issues such as the text colour displaying at the wrong time etc.

class YourCell: UICollectionViewCell {

    override func prepareForReuse() {
        super.prepareForReuse()
        
        titleLabel.text = // Your default grey colour
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM