iosswiftuicollectionview

How to tell if a CollectionViewCell is at the center of screen


I have a UICollecitonView that scrolls horizontally. I have a requirement such that when the user scrolls to the right or left, the collection view cell at the horizontal center of the screen is colored differently. The color needs to updated as each passes through the center.

Our UICollectionView shows three UICollectionViewCells at startup, so "center" is defined as the CGRect of the second UICollectionViewCell.

How to detect this? Is there an event that fires at scroll end? Also, how to tell if a CGRect rectangle is within another CGRect rectangle's bounds?


Solution

  • This answer will give you rough idea about

    1. how to get scrollView event callback.
    2. how to convert point or rect from one view coordinates to another view coordinates.
    3. how to get CollectionViewCell at certain point in CollectionView.

    You can change the code as per your requirement.

    1. Create a method as follow

        func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {
             
             let centerPoint = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
             let collectionViewCenterPoint = self.view.convert(centerPoint, to: collectionView)    
             
             if let indexPath = collectionView.indexPathForItem(at: collectionViewCenterPoint) { 
                    let collectionViewCell = collectionView.cellForItem(at: indexPath)
                    collectionViewCell?.backgroundColor = UIColor.red
             }
        }
    

    In above method we are trying to find the CollectionViewCell which is at the centre of the CollectionView. We are trying to get that CollectionViewCell's indexPath and update its background color.

    2. Implement below given ScrollViewDelegate methods

        func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
             self.scrollViewDidEndScrolling(scrollView)
        }
    
        func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
             if !decelerate {
                self.scrollViewDidEndScrolling(scrollView)
             }
        }
    

    We have to call our method from these ScrollViewDelegate methods. These methods gets called when collectionView stops scrolling.