使用页面控制器自动移动scrollview

问题描述 投票:0回答:2

嗨,我在我的应用程序中使用PageController

我已经在scrollView上插入了所有数据。

我想要做的是,我想像特定时间的页面控制一样自动移动scrollview

scrollView到达最后一页时,它再次快速调用所有页面并从第一个开始。

我想在最后一页完成后非常顺利地加载/获取第一页。

找到我的代码如下。

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)
    }
}
ios swift scroll uipagecontrol
2个回答
1
投票
@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.1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
            self.scrollView.scroll(topOffset:offSet, animated: true)
        }, completion: nil)
    }
}


extension UIScrollView {

    // Bonus: Scroll
    func scroll(topOffset:Float, animated: Bool) {
        let ofSetValue = CGPoint(x: topOffset, y: 0)
        setContentOffset(ofSetValue, animated: animated)
    }
}

0
投票

使用以下代码正常工作。

 @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.0, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
                self.scrollView.contentOffset.x = CGFloat(self.offSet)
            }, completion: nil)
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.