How to auto scroll UIScrollView using timer?

Viewed 24767

I have a UIScrollView to show images. I need a timer to show the images one after another, after every 5 seconds. How to initiate UIScrollView event to move to the next image after 5 seconds using the timer?

5 Answers

Swift version

Add the following properties

var offSet: CGFloat = 0

@IBOutlet weak var imagePageControl: UIPageControl!
@IBOutlet weak var imageScrollView: UIScrollView!

let imageArray = [your images]

Modify the viewDidLoad()

    override func viewDidLoad() {
    super.viewDidLoad()
    self.offSet = 0
    let timer = Timer.scheduledTimer(timeInterval: 8, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

    imagePageControl.numberOfPages = bannerArray.count
    imageScrollView.isPagingEnabled = true
    imageScrollView.contentSize.height = 200
    imageScrollView.contentSize.width = self.view.bounds.width * CGFloat(bannerArray.count)
    imageScrollView.showsHorizontalScrollIndicator = false

    imageScrollView.delegate = self

    for (index, image) in imageArray.enumerated() {
        let image = image
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFill
        imageView.frame.size.width = self.view.bounds.size.width
        imageView.frame.size.height = 200
        imageView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
        imageScrollView.addSubview(imageView)
    }
}

create this function for automatic scroll

    func autoScroll() {
    let totalPossibleOffset = CGFloat(imageArray.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.imageScrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}

Add this function for manual scroll

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.frame.size.width
    imagePageControl.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
}

Note: Though the question is specific to automatic scroll, I have added manual scroll as well. So that both automatic scroll and manual scroll work in tandem. Also, I have added a UIPageControl. Please remove the imagePageControl if you don't need it.

Related