UICollectionViewCell全屏显示时,分页很简单,只要一句代码collectView?.isPagingEnabled = true就搞定了。
但如果cell之间有间隙,例如:10pixel,上面的代码就会导致cell滑动后不居中,此时通过scrollViewWillEndDragging回调来处理比较好。直接贴上Swift代码,如下:
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
var item = ceil(scrollView.contentOffset.x/kScreenHeight)
print("scrollViewWillEndDragging \(velocity) \(targetContentOffset.pointee)")
if abs(velocity.x) > 1.0 || scrollView.contentOffset.x.truncatingRemainder(dividingBy: kScreenHeight) >= kScreenHeight/2 {
targetContentOffset.deinitialize()
var index = scrollView.contentOffset.x/kScreenHeight + 1
if velocity.x < 0 {
index = scrollView.contentOffset.x/kScreenWidth
item = floor(scrollView.contentOffset.x/kScreenWidth)
}
targetContentOffset.pointee = CGPoint(x:floor(index) * kScreenWidth + 5 * item, y:0)
}else {
targetContentOffset.deinitialize()
targetContentOffset.pointee = CGPoint(x:floor(scrollView.contentOffset.x/kScreenWidth)*kScreenWidth + 5 * item, y:0)
}
}