首页 > 解决方案 > 触摸滚动视图的幻灯片时暂停计时器?

问题描述

我正在尝试在我的滚动视图中自动滚动幻灯片。我实际上是在为我的入职屏幕做这个。但是,我希望计时器在用户触摸幻灯片时暂停一段时间,并在他移开手指时再次开始。

我正在做这样的事情,但这不适用于我要问的情况:

in viewDidLoad -
     timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)


@objc func autoScroll() {
        let totalPossibleOffset = CGFloat(topImages.count - 1) * self.view.bounds.size.width
        if offSet == totalPossibleOffset {
            //offSet = 0 // come back to the first image after the last image
            //timer.invalidate()
        }
        else {
            offSet += self.view.bounds.size.width
        }
        DispatchQueue.main.async() {
            UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
                self.scrollView.contentOffset.x = CGFloat(self.offSet)
            }, completion: nil)
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = scrollView.contentOffset.x / scrollView.frame.size.width
        pageControl.currentPage = Int(page)
        self.offSet = page * scrollView.frame.size.width // this updates offset value so that automatic scroll begins from the image you arrived at manually
    }

另外我还有第二个问题:当用户手动滑动到其他人时,如何再次启动计时器间隔。现在,当用户在 4 秒之前滑到另一张幻灯片(因为滑到另一张幻灯片需要 4 秒),比如说 2 秒,他将在 4-2 = 2 秒后滑到下一页,而不是 4 秒预期的。

标签: iosswiftuikit

解决方案


我认为您应该添加一些标志,例如

var isSlideTouched = false

在手势识别器中添加

isSlideTouched = true

以及 autoScroll() 中的一些代码

@objc func autoScroll() {
    if isSlideTouched {
        isSlideTouched = false
        return
    }

推荐阅读