Tusker/Tusker/Screens/Utilities/SegmentedPageViewController...

79 lines
3.0 KiB
Swift
Raw Normal View History

//
// SegmentedPageViewController.swift
// Tusker
//
// Created by Shadowfacts on 9/13/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import UIKit
class SegmentedPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let titles: [String]
let pageControllers: [UIViewController]
private(set) var currentIndex: Int!
var segmentedControl: UISegmentedControl!
init(titles: [String], pageControllers: [UIViewController]) {
self.titles = titles
self.pageControllers = pageControllers
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
self.dataSource = self
self.delegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
segmentedControl = UISegmentedControl(items: titles)
segmentedControl.addTarget(self, action: #selector(segmentedControlChanged), for: .valueChanged)
navigationItem.titleView = segmentedControl
segmentedControl.selectedSegmentIndex = 0
selectPage(at: 0, animated: false)
}
func selectPage(at index: Int, animated: Bool) {
let direction: UIPageViewController.NavigationDirection = currentIndex == nil ? .forward : index - currentIndex > 0 ? .forward : .reverse
setViewControllers([pageControllers[index]], direction: direction, animated: animated)
navigationItem.title = pageControllers[index].title
currentIndex = index
}
@objc func segmentedControlChanged() {
selectPage(at: segmentedControl.selectedSegmentIndex, animated: true)
}
// MARK: - Page View Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController),
index > 0 else { return nil }
return pageControllers[index - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController),
index < pageControllers.count - 1 else { return nil }
return pageControllers[index + 1]
}
// MARK: - Page View Controller Delegate
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
currentIndex = pageControllers.firstIndex(of: viewControllers!.first!)!
segmentedControl.selectedSegmentIndex = currentIndex
navigationItem.title = viewControllers!.first!.title
}
}