Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pffan91/1be33cd287902cfab0a63e51f770f0d9 to your computer and use it in GitHub Desktop.
Save pffan91/1be33cd287902cfab0a63e51f770f0d9 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?.firstIndex(of: viewController) {
let viewSize = fromView.frame
let scrollRight = controllerIndex > tabBarController.selectedIndex
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.3, delay: 0, usingSpringWithDamping: 0.87, initialSpringVelocity: 1, 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