Using a UISegmentedControl
to switch view controllers is very common, even Apple does it:
Let's build this using UIPageViewController
and UISegmentedControl
.
We start with a blank storyboard, drag out a UIPageViewController
and set it as the initial view controller. Then drag out two UIViewControllers
to switch between. We'll select the page view controller and choose Editor > Embed In > Navigation Controller.
Then we drag out a UISegmentedControl
and drop it into the title area of the navigation bar of our page view controller. Finally, we create an @IBAction
function that will get called when the selected segment changes.
The code is pretty straightforward, note the use of R.swift to grab those two view controllers from our storyboard. (covered in Bite #52).
func setViewControllerForIndex(index: Int) {
setViewControllers(
[index == 0 ? spaceshipsVC! : crewVC!],
direction: .Forward,
animated: false,
completion: nil
)
}
override func viewDidLoad() {
super.viewDidLoad()
spaceshipsVC = R.storyboard.main.spaceshipsVC
crewVC = R.storyboard.main.crewVC
setViewControllerForIndex(0)
}
@IBAction func segmentedControlChanged(sender: UISegmentedControl) {
setVCForIndex(sender.selectedSegmentIndex)
}
extension ViewController : UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if viewController == crewVC { return spaceshipsVC }
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if viewController == spaceshipsVC { return crewVC }
return nil
}
}
Download the complete project here: j.mp/bite055