【问题标题】:Enable only forward swiping in UICollectionView在 UICollectionView 中仅启用向前滑动
【发布时间】:2021-12-11 14:33:45
【问题描述】:

我有一个UICollectionView,我在其中显示一个UICollectionViewCell。每个单元格具有与collection view 相同的height 和width。

我想限制用户在进入下一个单元格后刷回UICollectionViewCell

有点像火种体验,虽然我的UICollectionView 中有Pagination enabled

【问题讨论】:

  • 你可以试试collectionView的委托方法**"func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)"**/

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


【解决方案1】:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    
    let indexPathOfVisible = collectionView.indexPath(for: collectionView.visibleCells.first ?? UICollectionViewCell())
    
    if indexPath.row < indexPathOfVisible?.row ?? 0 {
        collectionView.scrollToItem(at: indexPathOfVisible!, at: .right, animated: false)
    } 
}

【讨论】:

    【解决方案2】:

    您可以通过以下步骤做到这一点

    您必须在滚动结束后获取当前行并更新您的当前索引

    currentIndex
    

    对象 然后允许视图滚动或不滚动。 确保您已经计算出适当的单元格宽度,包括左右边缘和集合视图的单元格空间

    var currentIndex = 0
    var cellWidth = 0.0
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
                let row = scrollView.contentOffset.x / cellWidth
                currentIndex = Int(row)
            }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
            if scrollView.contentOffset.x < cellWidth * CGFloat(currentIndex){
                scrollView.contentOffset =  CGPoint(x: cellWidth * CGFloat(currentIndex), y: -20)
                scrollView.bounces = false
            } else {
                scrollView.bounces = true
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2014-11-27
      相关资源
      最近更新 更多