【问题标题】:Disable automatic scroll in UICollectionView if user is scrolling如果用户正在滚动,则禁用 UICollectionView 中的自动滚动
【发布时间】:2018-04-12 10:33:41
【问题描述】:

我已经实现了一个水平的UICollectionView,它会在 3 秒后自动滚动到下一个单元格。

一切正常,但我遇到了问题。

由于该函数会在 3 秒后自动触发,如果 NSTimer 两者同时发生,它会与用户的滚动条发生冲突。

例子:

用户在 3 秒功能触发的同时向左(向后)滚动,这将向右滚动(下一个单元格)。

我想知道是否有办法让我们说,如果用户自己正在滚动,则禁用自动滚动,如果用户停止滚动,几秒钟后重新启用它。

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    startTimer()
}

fileprivate func startTimer() {
    Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true)
}

@objc fileprivate func scrollToNextCell() {
    let cellSize = CGSize(width: width, height: height)
    let contentOffset = collectionView.contentOffset
    if collectionView.contentSize.width <= collectionView.contentOffset.x + cellSize.width {
        let rect = CGRect(x: 0, y: 0, width: cellSize.width, height: cellSize.height)
        collectionView.scrollRectToVisible(rect, animated: false)
    } else {
        let rect = CGRect(x: contentOffset.x + cellSize.width, y: 0, width: cellSize.width, height: cellSize.height)
        collectionView.scrollRectToVisible(rect, animated: true)
    }
}

这里最好的方法是什么?

一些东西:

集合视图检测到用户滚动它会禁用startTimer() 功能,然后如果用户停止滚动,则触发另一个等待Xn seconds 再次触发startTimer() 功能的功能。

然后,每次用户再次滚动时,它都会再次禁用startTimer() 以及启用startTimer()(如果它正在运行)的新功能。

我怎样才能做到这一点?

【问题讨论】:

    标签: ios uicollectionview swift4


    【解决方案1】:

    利用UIScrollViewDelegate

    // called on finger up as we are moving
    - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
        Invalidate Timer.
    }
    
    // called when scroll view grinds to a halt  
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
        Restart Timer.
    }
    

    替代方法

    使用deceleratingproperty。如果用户没有拖动(触摸向上)但滚动视图仍在移动,则返回 YES

    @objc fileprivate func scrollToNextCell() {
      if (!collectionView.isDecelerating) {
         //your code here
      }
    }
    

    【讨论】:

    • 哦.. 不知道Decelerating 属性只在触摸时触发,因为它是自动滚动的,我认为它们无论如何都会触发。我会尝试您的解决方案,稍后我会反馈。
    • 非常感谢
    猜你喜欢
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2020-08-11
    • 2016-11-03
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多