Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabBar icon bounce effect on selection like a Twitter app in Swift

How can I create a tab bar icon bounce effect like a Twitter app when I tap on one of them? look like it's scale down and after that back to normal.

enter image description here

Thank you.

like image 804
Sajad Avatar asked Sep 12 '25 06:09

Sajad


1 Answers

This is quite a simple solution that works for me. Subclass the UITabBarController and override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)

class AnimatedTabBarController: UITabBarController {

    private var bounceAnimation: CAKeyframeAnimation = {
        let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        bounceAnimation.values = [1.0, 1.4, 0.9, 1.02, 1.0]
        bounceAnimation.duration = TimeInterval(0.3)
        bounceAnimation.calculationMode = CAAnimationCalculationMode.cubic
        return bounceAnimation
    }()

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        // find index if the selected tab bar item, then find the corresponding view and get its image, the view position is offset by 1 because the first item is the background (at least in this case)
        guard let idx = tabBar.items?.index(of: item), tabBar.subviews.count > idx + 1, let imageView = tabBar.subviews[idx + 1].subviews.first as? UIImageView else {
            return
        }

        imageView.layer.add(bounceAnimation, forKey: nil)
    }
}

The result looks like this

Bounce in tab bar

like image 55
Igor Kulman Avatar answered Sep 14 '25 20:09

Igor Kulman