Search code examples
iosswiftnstimeruipagecontrol

work with UIPagecontrol using NSTimer in swift4


I am trying to add the UIPagecontrol using NSTimer for images sliding. but not able to get it. I have tried something which is given below.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var pagecontrol: UIPageControl!
    @IBOutlet weak var imgview: UIImageView!

     var tTime: Timer!
     var index = 0
     var items = ["1.png","11.png","111.png","1111.png"]

    override func viewDidLoad() {
        super.viewDidLoad()
        configurePageControl()
        let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
        // Do any additional setup after loading the view, typically from a nib.
    }

    func configurePageControl() {
        self.pagecontrol.numberOfPages = items.count
        self.pagecontrol.currentPage = 0
        self.pagecontrol.tintColor = UIColor.red
        self.pagecontrol.pageIndicatorTintColor = UIColor.black
        self.pagecontrol.currentPageIndicatorTintColor = UIColor.green
    }

    @objc func update()  {
        index = index + 1
    }
}

If anyone helps,Would be great.Thank in advance.


Solution

  • Change your

    @objc func update()  {
            index = index + 1
    
        }
    

    function to

    @objc func update()  {
        index = index + 1
    
        if index >= items.count {
            index = 0
        }
        imgview.image = UIImage(named: items[index])
        pagecontrol.currentPage = index
    }
    

    And it should work.