Skip to content

Instantly share code, notes, and snippets.

@illescasDaniel
Forked from benvium/MyTabBar.m
Last active April 11, 2022 14:03
Show Gist options
  • Save illescasDaniel/6689461ccd396f0536e4f2e5f43befe8 to your computer and use it in GitHub Desktop.
Save illescasDaniel/6689461ccd396f0536e4f2e5f43befe8 to your computer and use it in GitHub Desktop.
[Updated to Swift 4] - UITabBarController slide animation. Slide left and right when tabs are selected. Based on code from StackOverflow
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if let fromView = tabBarController.selectedViewController?.view,
let toView = viewController.view, fromView != toView,
let controllerIndex = self.viewControllers?.index(of: viewController) {
let viewSize = fromView.frame
let scrollRight = controllerIndex > tabBarController.selectedIndex
// Avoid UI issues when switching tabs fast
if fromView.superview?.subviews.contains(toView) == true { return false }
fromView.superview?.addSubview(toView)
let screenWidth = UIScreen.main.bounds.size.width
toView.frame = CGRect(x: (scrollRight ? screenWidth : -screenWidth), y: viewSize.origin.y, width: screenWidth, height: viewSize.size.height)
UIView.animate(withDuration: 0.25, delay: TimeInterval(0.0), options: [.curveEaseOut, .preferredFramesPerSecond60], animations: {
fromView.frame = CGRect(x: (scrollRight ? -screenWidth : screenWidth), y: viewSize.origin.y, width: screenWidth, height: viewSize.size.height)
toView.frame = CGRect(x: 0, y: viewSize.origin.y, width: screenWidth, height: viewSize.size.height)
}, completion: { finished in
if finished {
fromView.removeFromSuperview()
tabBarController.selectedIndex = controllerIndex
}
})
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment