tab点击,图片放大缩小动画

来源:互联网 发布:填表软件 编辑:程序博客网 时间:2024/05/19 19:59

项目中这次改版应产品要求加入tabbar点击做放大缩小动画,只改变图片,标题不做动画。先看效果图未命名.gif

Demo地址

图片做放大缩小动画,很好做。用CoreAnimation的帧动画就可以实现。不过貌似系统并没有开出开关于tabbar上的imageView这个属性。其实我们找到在tab上的imageView,这一切问题就好解决了。
直接上代码
声明一个tab继承系统tabbar#import <UIKit/UIKit.h>@interface FFTabBar : UITabBar@end
.m文件里可以通过layoutSubviews找到需要做动画的tabItem- (void)layoutSubviews{    [super layoutSubviews];    for (UIControl *tabBarButton in self.subviews) {        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];        }    }}
实现点击方法,找系统的私有属性UITabBarSwappableImageView 。这个就是我们今天要找的tab上的imageView
- (void)tabBarButtonClick:(UIControl *)tabBarButton{    NSInteger index = [self.items indexOfObject:self.selectedItem];    if (index != self.selectTabBarTag) {        for (UIView *imageView in tabBarButton.subviews) {            if ([imageView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {                [FFTabModel selectTabBarDoScaleAnimationWithView:imageView];            }        }    }    self.selectTabBarTag = index;}#pragma mark - Associated Object- (void)setSelectTabBarTag:(NSInteger)object{    objc_setAssociatedObject(self, @selector(selectTabBarTag), @(object), OBJC_ASSOCIATION_RETAIN_NONATOMIC);}- (NSInteger)selectTabBarTag{    return [objc_getAssociatedObject(self, @selector(selectTabBarTag)) integerValue];}
上边通过私有属性UITabBarSwappableImageView 找到我们想要的imageView然后做相应的动画效果,这里通过runtime运行时,添加属性为NSInteger的selectTabBarTag。目的就是防止重复点击动画,
但是有时候我们项目中往往第一次进入App选择的并不是第0个item,有存在其他情况。这时候我们就要考虑动画保障点击item无论是任何一个的时候都要肯定出现动画,这里我做了一个判断
- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        //为保证动画不会重复以及点击动画的正确性,特增加selectTabBarTag, 保证selectTabBarTag和当前tabBarController.selectedIndex一致。        self.selectTabBarTag = 1;    }    return self;}

到这里就写完了,Demo为项目源码。可放心直接拿去使用

Demo地址