ios - 点击后启用分页的 UICollectionView 滚动问题

标签 ios swift uicollectionview uicollectionviewcell

我有一个 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))

        }

    }

最佳答案

如果你想要当前页面,你应该像这样从 ScrollView 获取页面

 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / collectionCustom.frame.width) // You can change width according you 
    pageControl.currentPage = Int(pageNumber)

}

关于ios - 点击后启用分页的 UICollectionView 滚动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455897/

相关文章:

ios - UIAutomation 和 XCTestCase : how to wait for a button to activate

objective-c - iOS 上是否有类似 MVVM 的 objective-c 框架?

ios - PFQueryTableViewController 分页不适用于 heightForRowAtIndexPath

ios - 在底部启动 UICollectionView

swift - TableView 内的 CollectionView 滚动ViewDidEndDecelerating 崩溃

iphone - 我仍然可以将 iOS 3.2 SDK 编译的应用程序上传到 iTunesConnect

ios - 从一个 UIViewController 转到另一个而不使用导航(segue)iOS 6

string - Swift 可以打印 AnyObject,但不能从 AnyObject 创建字符串

swift - RealmSwift RLM异常

arrays - 在 Swift 中从 Firebase 填充的多维数组