CollectionView单元格在水平滚动之后移动到右侧
我有一个与我的CollectionView的大小相同的collectionView单元格,即一次显示一个单元格,我希望单元格之间的最小间隔为10,问题是当我滚动单元格时,单元格没有正确安装整个屏幕,并在每次滚动后增加单元格的移动。 (检查屏幕截图以便更好地理解)
我假设你已经设置了集合视图的pagingEnabled
。 它从UIScrollView
inheritance这个属性(因为UICollectionView
是UIScrollView
的子类)。
问题是收集视图使用自己的宽度(您的文章中的320点)作为页面的宽度。 每个单元格的宽度与集合视图的宽度相同,但是在单元格之间有一个10点的“装订线”。 这意味着从单元格0的左边缘到单元格1的左边缘的距离是320 + 10 = 330点。 因此,当您滚动显示单元格1时,集合视图停止在偏移量320(其自身宽度)滚动,但单元格1实际上从偏移量330开始。
最简单的解决方法是closurespagingEnabled
并通过在您的集合视图委托中覆盖scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)
来实现自己的分页,如下所示:
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return } let pageWidth = scrollView.bounds.size.width + flowLayout.minimumInteritemSpacing let currentPageNumber = round(scrollView.contentOffset.x / pageWidth) let maxPageNumber = CGFloat(collectionView?.numberOfItems(inSection: 0) ?? 0) // Don't turn more than one more page when decelerating, and don't go beyond the first or last page. var pageNumber = round(targetContentOffset.pointee.x / pageWidth) pageNumber = max(0, currentPageNumber - 1, pageNumber) pageNumber = min(maxPageNumber, currentPageNumber + 1, pageNumber) targetContentOffset.pointee.x = pageNumber * pageWidth }
您还需要将项目大小设置为与设备屏幕大小相匹配,并将减速率设置为快速:
override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let collectionView = collectionView else { return } flowLayout.itemSize = collectionView.bounds.size collectionView.decelerationRate = UIScrollViewDecelerationRateFast }
结果:
原因在于,在设置单元格宽度(320)的时候,您没有采用minimum separation of 10
。 因此,这个10
每次都会累积起来进行滚动。
所以你必须在设置宽度时减去320中的10,所以宽度应该是310 IMO。
- 使用NSRunloop避免事件驱动的代码
- 推送通知不在iOS 10上收到,但在iOS 9和之前的版本上
- UIViewController生命周期调用结合状态恢复
- iOS Core Data获取新插入的,尚未保存的对象
- iOS开发:更新我的iPhone 4到iOS 4.3 Beta 3后,我的应用程序说“这个游戏不被Game Center识别”
- 在iOS聊天中设置QuickBlox QBUUser中的聊天/头像
- AFNetworking:setRedirectResponseBlock在我的类NSURLResponse总是返回空值
- XCode 7.0.1,机器人和服务器5.0.4:testing目标“xx”遇到错误 – 超时等待120秒模拟器启动
- IOS支持同时wifi和3g / 4g连接吗?