Skip to content

Instantly share code, notes, and snippets.

@krodak
Last active March 3, 2018 19:15
Show Gist options
  • Save krodak/2bd8139c5f69b9434008 to your computer and use it in GitHub Desktop.
Save krodak/2bd8139c5f69b9434008 to your computer and use it in GitHub Desktop.
UIViewController extension for hidding UITabBarController
import UIKit
extension UIViewController {
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() -> Bool {
return self.tabBarController?.tabBar.frame.origin.y < UIScreen.mainScreen().bounds.height
}
}
@alkanyunus
Copy link

So force unwrapping causes crashed. Be aware of that!

@brindy
Copy link

brindy commented Feb 3, 2018

I created a version here: https://gist.github.com/brindy/b93d0cd0ce4ca3560225ade23f4cf35e

I figured if you make it an extension of the UITabBarViewController you can get rid of a lot of that optional/force unwrapping stuff. Then just call it safely from your view controller (in viewWillAppear usually) like this:

tabBarController?.setTabBarVisible(visible: false, animated: true)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment