1 import UIKit 2 3 class ViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { 4 5 @IBOutlet weak var redBtn: UIButton! 6 @IBOutlet weak var yellowBtn: UIButton! 7 @IBOutlet weak var blueBtn: UIButton! 8 9 var vcArr = NSMutableArray.init() 10 var pageVC: UIPageViewController! 11 var currentIndex: Int { 12 get { 13 if redBtn.isSelected { 14 return redBtn.tag 15 } else if yellowBtn.isSelected { 16 return yellowBtn.tag 17 } else if blueBtn.isSelected { 18 return blueBtn.tag 19 } else { 20 return 0 21 } 22 } 23 24 set { 25 if newValue == 0 { 26 redBtn.isSelected = true 27 yellowBtn.isSelected = false 28 blueBtn.isSelected = false 29 } else if newValue == 1 { 30 redBtn.isSelected = false 31 yellowBtn.isSelected = true 32 blueBtn.isSelected = false 33 } else if newValue == 2 { 34 redBtn.isSelected = false 35 yellowBtn.isSelected = false 36 blueBtn.isSelected = true 37 } 38 } 39 } 40 41 42 override func viewDidLoad() { 43 super.viewDidLoad() 44 // Do any additional setup after loading the view, typically from a nib. 45 46 let sb = UIStoryboard.init(name: "Main", bundle: nil) 47 48 for tempID in ["RedViewController", "YellowViewController", "BlueViewController"] { 49 let tempVC = sb.instantiateViewController(withIdentifier: tempID) 50 vcArr.add(tempVC) 51 } 52 53 pageVC = self.childViewControllers.first as! UIPageViewController! 54 pageVC.delegate = self 55 pageVC.dataSource = self 56 pageVC.setViewControllers([vcArr.object(at: 0) as! UIViewController], direction: .forward, animated: true, completion: nil) 57 currentIndex = 0 58 } 59 60 @IBAction func handleBtnPressed(_ sender: UIButton) { 61 if currentIndex != sender.tag { 62 currentIndex = sender.tag 63 pageVC.setViewControllers([vcArr.object(at: currentIndex) as! UIViewController], direction: .forward, animated: false, completion: nil) 64 } 65 } 66 67 override func didReceiveMemoryWarning() { 68 super.didReceiveMemoryWarning() 69 // Dispose of any resources that can be recreated. 70 } 71 72 func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { 73 let index = vcArr.index(of: viewController) 74 if index - 1 < 0 { 75 return nil 76 } else { 77 return vcArr.object(at: index - 1) as? UIViewController 78 } 79 } 80 81 func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { 82 let index = vcArr.index(of: viewController) 83 if index + 1 >= vcArr.count { 84 return nil 85 } else { 86 return vcArr.object(at: index + 1) as? UIViewController 87 } 88 } 89 90 func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { 91 currentIndex = vcArr.index(of: pageViewController.viewControllers?[0] as Any) 92 } 93 }