【问题标题】:Stop the autoscroll in scrollview on user interaction swift快速停止用户交互时滚动视图中的自动滚动
【发布时间】:2019-10-13 14:59:02
【问题描述】:

我在我的应用程序中使用页面控制器。

每 3 秒自动滚动一次,并且当前位置也会根据用户自定义滑动而改变。

但是当用户在我想停止自动滚动时手动滑动滚动视图时,我遇到了一个问题。

请用我下面的代码查找。

var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
    super.viewDidLoad()

    slides = createSlides()
    setupSlideScrollView(slides: slides)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = 0
    view.bringSubview(toFront: pageControl)

    let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

}

@objc func autoScroll() {
    let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    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)
    }
}

【问题讨论】:

  • 检查 currentPage 和幻灯片数组计数

标签: ios swift uiscrollview uipagecontrol


【解决方案1】:

代码未经测试,您应该检查当前索引和幻灯片总数

创建一个如下所示的全局索引并更改您的条件。您还需要在滑动功能时管理此索引,并在滑动时使您的计时器无效。您的计时器对象应该在全局中

timer.invalidate()



 var currentPage = 0
        @objc func autoScroll() {
            let totalPossibleOffset = 0
            if currentPage == slides.count {
                currentPage = 0 // come back to the first image after the last image
                totalPossibleOffset = 0
            }
            else {
currentPage = currentPage + 1
                totalPossibleOffset = currentPage * self.view.bounds.size.width

            }
            DispatchQueue.main.async() {
                UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
                    self.scrollView.contentOffset.x = CGFloat(totalPossibleOffset)
                }, completion: nil)
            }
        }

【讨论】:

    【解决方案2】:

    添加滚动视图委托并在调用时使用scrollViewDidEndDragging 方法,只需重置您的计时器,以便在 3 秒后重新开始,它会照常工作。

    【讨论】:

    • 不,我使用这段代码它不起作用 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { timer = Timer.scheduledTimer(timeInterval: 500, target: self, selector: #selector (自动滚动),用户信息:无,重复:真)}
    • timer.invalidate() 首先使您的计时器无效然后再次启动它,时间间隔是 500?
    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多