前言
????對(duì)于自定義tabBar。我們?cè)诤芏鄷r(shí)候需要在點(diǎn)擊tabbar按鈕時(shí)會(huì)有動(dòng)畫效果。在動(dòng)畫界,有一個(gè)非常非常強(qiáng)大的動(dòng)畫框架Lottie。只要你的UI設(shè)計(jì)師給力,理論上可以實(shí)現(xiàn)任意動(dòng)畫,而且只需要幾行代碼。接下來是我研究的使用lottie動(dòng)畫來實(shí)現(xiàn)(也許有更簡便的方式,希望留言告知)。先看一下效果

Nov-26-2019 15-46-59.gif
實(shí)現(xiàn)原理
????簡單一句話,lottie動(dòng)畫的載體控件本質(zhì)上是一個(gè)UIView,我們要做的就將這個(gè)UIView通過addSubView的方式加到tabBarItem上。
????為了使其位置準(zhǔn)確,我們最理想的是將lottie的位置和大小放置的和原生的image的位置大小一致。因此我們需要找到原生的image的載體UIImageView(應(yīng)該可以想象的到,原生的tabBarItem必有一個(gè)UIImageView)。
????接下來是找到這個(gè)原生的UIImageView,看代碼
//這個(gè)是自定義UITabBar的layoutSubviews方法
- (void)layoutSubviews {
[super layoutSubviews];
//添加lottie的操作,只可以做一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//三個(gè)lottieView
DLLottieView *view = [DLLottieView animationWithSelectName:@"arrow_select" unselectName:@"arrow_unselect"];
DLLottieView *view1 = [DLLottieView animationWithSelectName:@"second_select" unselectName:@"second_unselect"];
DLLottieView *view2 = [DLLottieView animationWithSelectName:@"arrow_select" unselectName:@"arrow_unselect"];
self.itemArr = @[view,view1,view2];
NSInteger flag = 0;
//遍歷UITabbar的子控件
for (UIView *barBtn in self.subviews) {
//其中有一個(gè)子控件是UITabBarButton類型。
if ([barBtn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
UIImageView *tabBarSwappableImageView = [[UIImageView alloc] init];;
//在UITabBarButton的子控件中有一個(gè)UITabBarSwappableImageView類型,這就是tabBarItem用來展示圖片的imageView
for (UIView *subView in barBtn.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
tabBarSwappableImageView = (UIImageView *)subView;
}
}
//拿到這個(gè)imageView,給它添加lottie
[tabBarSwappableImageView addSubview:self->_itemArr[flag]];
//設(shè)置lottie的位置大小
CGFloat width = self->_needSetBiggerItem && flag == self->_biggerItemIndex ? 52 : 32;
CGFloat y = self->_needSetBiggerItem && flag == self->_biggerItemIndex ? 10 : 0;
self->_itemArr[flag].frame = CGRectMake(0, 0, width, width);
self->_itemArr[flag].center = CGPointMake(tabBarSwappableImageView.center.x, tabBarSwappableImageView.center.y - y);
flag ++;
}
}
[self playAnimationForIndex:0];
});
}
????代碼中的注釋說的比較詳細(xì)。總而言之就是找到原生的Imageview,給它加上LottieView,再設(shè)置上合適的大小位置。
????上面這段是核心代碼,當(dāng)然還有一些處理點(diǎn)擊動(dòng)畫的簡單方法,具體可以看demo
其他
????里面還可以順便實(shí)現(xiàn)中間按鈕凸出這類需求。