Перемещение прокрутки автоматически с помощью контроллера страницы - PullRequest
0 голосов
/ 18 апреля 2019

Привет, я использую 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)
    }
}

Ответы [ 2 ]

1 голос
/ 18 апреля 2019
@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 голосов
/ 18 апреля 2019

Используйте следующий код, работающий нормально.

 @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)
        }
    }
...