UICollectionView滚动问题,在点击后启用分页
问题描述:
我有一个collectionView
,当我点击第二页中的新单元时,返回第一个单元格。UICollectionView滚动问题,在点击后启用分页
虽然它应该是第二页,但我在第二页获得Page 0.0,在第一页获得0.0。
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth = collectionCustom.frame.size.width
let page = floor((collectionCustom.contentOffset.x - pageWidth/2)/pageWidth) + 1
print("Page number: \(page)")
}
我什么都没有发生在didSelectItem
方法,所以为什么我得到那个卷轴?
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: (inout CGPoint)) {
let pageWidth: Float = Float(collectionCustom.frame.width)
// width + space
let currentOffset: Float = Float(collectionCustom.contentOffset.x)
let targetOffset: Float = Float(targetContentOffset.x)
var newTargetOffset: Float = 0
if targetOffset > currentOffset {
newTargetOffset = ceilf(currentOffset/pageWidth) * pageWidth
}
else {
newTargetOffset = floorf(currentOffset/pageWidth) * pageWidth
}
if newTargetOffset < 0 {
newTargetOffset = 0
}
else if newTargetOffset > Float(collectionCustom.contentSize.width) {
newTargetOffset = Float(collectionCustom.contentSize.width)
}
targetContentOffset.x = CGFloat(currentOffset)
collectionCustom.setContentOffset(CGPoint(x: CGFloat(newTargetOffset), y: CGFloat(0)), animated: true)
var index: Int = Int(newTargetOffset/pageWidth)
var cell: UICollectionViewCell? = collectionCustom.cellForItem(at: IndexPath(item: index, section: 0))
cell = collectionCustom.cellForItem(at: IndexPath(item: index + 1, section: 0))
}
}
答
如果你想当前页面不是你应该从滚动视图让你页面,因为这
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x/collectionCustom.frame.width) // You can change width according you
pageControl.currentPage = Int(pageNumber)
}
+0
这实际上已经为我工作。谢谢! – Christian
+0
@Christian欢迎队友 –
你可以添加你所遇到的行为和所期望的行为更多的描述? – nathan
您在问题中放入的代码中没有任何内容导致问题。您需要包含更多代码或尝试自己调试,并添加更多调试信息。 – Fogmeister
我想'collectionView'每页显示4个单元格,这是正确的,但是当我有5到7个单元格时,它不会显示日志中的下一页,这就是为什么我滚动回来第一个单元格。它适用于8个对象,4个倍数相同。理想情况下,如果我有7个对象,我希望看到3个单元格,等等,但它始终显示我4。 – Christian