Skip to content

Instantly share code, notes, and snippets.

@ahmed-abdurrahman
Created May 2, 2017 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmed-abdurrahman/dcfa0ec1ac45b45af20c7c9d4329e068 to your computer and use it in GitHub Desktop.
Save ahmed-abdurrahman/dcfa0ec1ac45b45af20c7c9d4329e068 to your computer and use it in GitHub Desktop.
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