为系统UITabBar添加点击动画

遍历tabbar,找到UITabBarButton这个类就可以

1.创建SJCTabBar

.h

#import 

@interface SJCTabBar : UITabBar 

@end

.m 自己可以在tabBarButtonClick方法中创建各种动画

#import "SJCTabBar.h"
@interface SJCTabBar ()
@property(strong,nonatomic) UIControl *lastTabBarButton;
@end
@implementation SJCTabBar

- (void)layoutSubviews
{
    [super layoutSubviews];
    //添加动画的
    for (UIControl *tabBarButton in self.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

- (void)tabBarButtonClick:(UIControl *)tabBarButton
{
    
    if (tabBarButton == self.lastTabBarButton) {
        return;
    }
    
//    //类似淘宝的点击动画
//    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
//    animation.keyPath = @"transform.scale";
//    //                animation.values = @[@1.0,@1.1,@0.9,@1.05,@0.95,@1.02,@1.0];
//    animation.values = @[@0.618,@1.0];
//    animation.duration = 0.15;
//    animation.calculationMode = kCAAnimationCubic;
//    //把动画添加上去就OK了
//    [tabBarButton.layer addAnimation:animation forKey:nil];
//    if ([tabBarButton valueForKeyPath:@"_selected"]) {
//        return;
//    }
        for (UIView *imageView in tabBarButton.subviews) {
            if ([imageView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
                //需要实现的帧动画,这里根据需求自定义
                CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
                animation.keyPath = @"transform.scale";
                animation.values = @[@1, @1.2, @0.9, @1.1, @0.95, @1.05, @1];
                animation.duration = 0.618;
                animation.calculationMode = kCAAnimationCubic;
                //把动画添加上去就OK了
                [imageView.layer addAnimation:animation forKey:nil];
            }
        }
    self.lastTabBarButton = tabBarButton;
    
}
@end

2. 利用KVC赋值

SJCTabBar *tabbar = [[SJCTabBar alloc] init];
    [self setValue:tabbar forKeyPath:@"tabBar"];

你可能感兴趣的:(为系统UITabBar添加点击动画)