TabBar图标反弹对选择的影响,例如Swift中的Twitter应用程序

Saj*_*jad 3 uitabbarcontroller uitabbaritem uitabbar ios swift

当我点击其中一个时,如何创建类似Twitter应用程序的标签栏图标弹跳效果?看起来像按比例缩小,然后又恢复正常。

在此处输入图片说明

谢谢。

Igo*_*man 5

这是一个对我有用的非常简单的解决方案。子类UITabBarController和重写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)
    }
}
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样

标签栏弹跳