[英]How to tell if a CollectionViewCell is at the center of screen
我有一個UICollecitonView
可以水平滾動。 我有一個要求,即當用戶向右或向左滾動時,屏幕水平中心的集合視圖單元格的顏色會有所不同。 當每種顏色穿過中心時,顏色都需要更新。
我們的UICollectionView在啟動時顯示了三個UICollectionViewCell
,因此將“ center”定義為第二個UICollectionViewCell
。
如何檢測呢? 滾動端是否會觸發事件? 另外,如何判斷CGRect矩形是否在另一個CGRect矩形的邊界內?
這個答案將使您對1.如何獲取scrollView事件回調有一個大概的了解。 2.如何將點或矩形從一個視圖坐標轉換為另一視圖坐標。 3.如何在CollectionView的特定位置獲取CollectionViewCell。
您可以根據需要更改代碼。
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
}
}
在上面的方法中,我們試圖找到位於CollectionViewCell
中心的CollectionView
。 我們正在嘗試獲取CollectionViewCell
的indexPath並更新其背景色。
2.實現以下給定的ScrollViewDelegate
方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.scrollViewDidEndScrolling(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
self.scrollViewDidEndScrolling(scrollView)
}
}
我們必須從這些ScrollViewDelegate
方法中調用我們的方法。 當collectionView
停止滾動時,將調用這些方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.