quanghuy9742
6/23/2018 - 2:14 PM

#crollanimation #tabbar #tabbarcontroller

#crollanimation #tabbar #tabbarcontroller

https://stackoverflow.com/questions/5161730/iphone-how-to-switch-tabs-with-an-animation

// DELEGATE
UICollectionViewController {
	self.delegate = self
}

ViewController {
	collectionView.delegate = self
}


// EXTENSION

extension TabBarViewController: UITabBarControllerDelegate {
    
    public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if let nextVCIndex = tabBarController.viewControllers?.index(of: viewController) {
            guard let fromView = tabBarController.selectedViewController?.view else {
                return false
            }
            
            guard let toView = viewController.view else {
                return false
            }
            
            if fromView == toView {
                return false
            }
            
            let isCrollRight = selectedIndex < nextVCIndex
            
            fromView.superview!.addSubview(toView)
            let width = fromView.frame.width
            let height = fromView.frame.height
            
            toView.frame = CGRect(x: (isCrollRight ? width : -width), y: fromView.frame.origin.y, width: width, height: height)
            
            UIView.animate(withDuration: 0.3, animations: {() -> Void in
                fromView.frame.origin = CGPoint(x: (isCrollRight ? -width : width), y: fromView.frame.origin.y)
                toView.frame.origin = CGPoint(x: 0, y: fromView.frame.origin.y)
            }) {(finished) -> Void in
                fromView.removeFromSuperview()
                
                // Nếu không thêm line này app sẽ bị crash khi user change tab quá nhanh và nhiều lần liên tiếp
                self.selectedIndex = nextVCIndex
            }
        }
        return true
    }
    
}