TabBar 添加点击动画效果

引言:

正常情况下,我们点击tabbar都只有一个变色效果,但有时候,如果我们想给它添加一个点击动画,该如何做呢?


# 一. 效果图


# 二. 代码实现

原理:利用UITabBarController代理 实现,在 tabbar 的 didSelectItem代理里添加动画效果。

#import "TabBarController.h"


@interface TabBarController ()<UITabBarDelegate>

@property (nonatomic, assign) NSInteger indexFlag;

@end


@implementation TabBarController

#pragma mark - ------ UITabBarDelegate ------

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    
    NSInteger index = [self.tabBar.items indexOfObject:item];
    
    if (index != self.indexFlag) { // 判断是否是当前选中的
        
        NSMutableArray *array = [NSMutableArray array];
        for (UIView *btn in self.tabBar.subviews) {
            if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
                [array addObject:btn];
            }
        }
        
        /// 缩放动画效果,并回到原位
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        //速度控制函数,控制动画运行的节奏
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.fromValue      = [NSNumber numberWithFloat:0.9];      // 初始伸缩倍数
        animation.toValue        = [NSNumber numberWithFloat:1.1];      // 结束伸缩倍数
        animation.duration       = 0.2;                                 // 执行时间
        animation.repeatCount    = 1;                                   // 执行次数
        animation.autoreverses   = YES;                                 // 完成动画后会回到执行动画之前的状态
        
        UIControl *btn = array[index];
        [btn.layer addAnimation:animation forKey:nil];
        
        self.indexFlag = index;
    }
}