/taby_parentvc.swift Secret
Created
May 2, 2017 12:01
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParentViewController: UIViewController { | |
enum TabIndex : Int { | |
case firstChildTab = 0 | |
case secondChildTab = 1 | |
} | |
@IBOutlet weak var segmentedControl: TabySegmentedControl! | |
@IBOutlet weak var contentView: UIView! | |
var currentViewController: UIViewController? | |
lazy var firstChildTabVC: UIViewController? = { | |
let firstChildTabVC = self.storyboard?.instantiateViewController(withIdentifier: "FirstViewControllerId") | |
return firstChildTabVC | |
}() | |
lazy var secondChildTabVC : UIViewController? = { | |
let secondChildTabVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewControllerId") | |
return secondChildTabVC | |
}() | |
// MARK: - View Controller Lifecycle | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
segmentedControl.initUI() | |
segmentedControl.selectedSegmentIndex = TabIndex.firstChildTab.rawValue | |
displayCurrentTab(TabIndex.firstChildTab.rawValue) | |
} | |
override func viewWillDisappear(_ animated: Bool) { | |
super.viewWillDisappear(animated) | |
if let currentViewController = currentViewController { | |
currentViewController.viewWillDisappear(animated) | |
} | |
} | |
// MARK: - Switching Tabs Functions | |
@IBAction func switchTabs(_ sender: UISegmentedControl) { | |
self.currentViewController!.view.removeFromSuperview() | |
self.currentViewController!.removeFromParentViewController() | |
displayCurrentTab(sender.selectedSegmentIndex) | |
} | |
func displayCurrentTab(_ tabIndex: Int){ | |
if let vc = viewControllerForSelectedSegmentIndex(tabIndex) { | |
self.addChildViewController(vc) | |
vc.didMove(toParentViewController: self) | |
vc.view.frame = self.contentView.bounds | |
self.contentView.addSubview(vc.view) | |
self.currentViewController = vc | |
} | |
} | |
func viewControllerForSelectedSegmentIndex(_ index: Int) -> UIViewController? { | |
var vc: UIViewController? | |
switch index { | |
case TabIndex.firstChildTab.rawValue : | |
vc = firstChildTabVC | |
case TabIndex.secondChildTab.rawValue : | |
vc = secondChildTabVC | |
default: | |
return nil | |
} | |
return vc | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment