Search code examples
iosswift3timeruiviewcontrolleruipageviewcontroller

change pages in UIPageViewController Automatically with timer in swift 3?


I have UIPageViewController that Contains 4 view Controllers

I set the timer for changing view controllers automatically(going to the next view controllers) - This timer and method will work But the problem is that It works Just for first Slide and when the app will run and after 5 seconds the UIPageViewController will show the second slide But after that nothing will happen ! This Is the Code That I used

lazy var VCArr : [UIViewController] = {

    return [self.VCInstance(name : "VC1"),
            self.VCInstance(name : "VC2"),
            self.VCInstance(name :"VC3"),
            self.VCInstance(name :"VC4")]
}()

func changeSlide() {

    print("Slide Change!")


    guard let currentViewController = self.VCArr.first  else { return }

            guard let nextViewController = dataSource?.pageViewController( self, viewControllerAfter: currentViewController ) else { return }

            setViewControllers([nextViewController], direction: .forward, animated: true, completion: nil)

    }

var tTime: Timer!

override func viewDidLoad() {
    super.viewDidLoad()


    tTime = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(changeSlide), userInfo: nil, repeats: true)


    }

I think the problem is in this line

guard let currentViewController = self.VCArr.first  else { return }

But I don't know how to change this line to work fine


Solution

  • Try this:

    You can change view controller by index of VCArr.

    var index = 0
    
    func changeSlide() {
        index + 1
        if index < self.VCArr.count {
            setViewControllers([VCArr[index]], direction: .forward, animated: true, completion: nil)
        }
        else {
            index = 0
            setViewControllers([VCArr[0]], direction: .forward, animated: true, completion: nil)
    
        }
    }