简体   繁体   English

如何判断CollectionViewCell是否在屏幕中央

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

I have a UICollecitonView that scrolls horizontally. 我有一个UICollecitonView可以水平滚动。 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 UICollectionViewCell s at startup, so "center" is defined as the CGRect of the second UICollectionViewCell . 我们的UICollectionView在启动时显示了三个UICollectionViewCell ,因此将“ center”定义为第二个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? 另外,如何判断CGRect矩形是否在另一个CGRect矩形的边界内?

This answer will give you rough idea about 1. how to get scrollView event callback. 这个答案将使您对1.如何获取scrollView事件回调有一个大概的了解。 2. how to convert point or rect from one view coordinates to another view coordinates. 2.如何将点或矩形从一个视图坐标转换为另一视图坐标。 3. how to get CollectionViewCell at certain point in CollectionView. 3.如何在CollectionView的特定位置获取CollectionViewCell。

You can change the code as per your requirement. 您可以根据需要更改代码。

1. Create a method as follow 1.创建如下方法

    func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {

         let centerPoint = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.minY)
         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 . 在上面的方法中,我们试图找到位于CollectionViewCell中心的CollectionView We are trying to get that CollectionViewCell 's indexPath and update its background color. 我们正在尝试获取CollectionViewCell的indexPath并更新其背景色。

2. Implement below given ScrollViewDelegate methods 2.实现以下给定的ScrollViewDelegate方法

    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. 我们必须从这些ScrollViewDelegate方法中调用我们的方法。 These methods gets called when collectionView stops scrolling. collectionView停止滚动时,将调用这些方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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