当我在第二页中点击新单元格时,我有collectionView
返回第一个单元格。
虽然它应该是第二页,但我在第二页中得到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))
}
}
答案 0 :(得分:2)
如果您想要当前页面,那么您应该从scrollview页面获取此页
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / collectionCustom.frame.width) // You can change width according you
pageControl.currentPage = Int(pageNumber)
}