前幾天看到Google Design guidelines - Components - Bottom(點擊文字跳轉(zhuǎn)丛楚,可能要翻墻)上的TabBar動畫吊说,試著寫了一下滤蝠,比較簡陋,僅供娛樂若河,
Github搜索 ZHTabBarAimation
效果
縮放
ZHTabBarAnimationStyleScale
位移
ZHTabBarAnimationStyleTranslation
實現(xiàn)思路
比較簡單的實現(xiàn)方法平道,縮放就是在tabBarButton的點擊方法中對self.imageView 和 self.titleLabel執(zhí)行縮放動畫。
位移動畫灼舍,在每次選中tabBarButton時以動畫的形式改變button的frame吼和,同時對tabBar中所有的button的imageView和titleLabel重新布局,可以在button的layoutSubViews方法里執(zhí)行骑素,且不需要添加動畫炫乓,因為button自己已經(jīng)在執(zhí)行動畫了。
關(guān)鍵代碼
項目中用到了自定UITabBar,繼承自UIView厢岂。另外還有通過模型設(shè)置tabBarButton的子控件值光督,具體的實現(xiàn)方法百度谷歌一大堆,這里不寫了塔粒。這里只貼出和動畫部分相關(guān)的代碼结借。
縮放動畫
ZHTabBarButton.m
// 在button的seSelected方法中調(diào)用
- (void)selectedScaleAnimation:(BOOL)selected
{
[UIView animateWithDuration:0.3 animations:^{
if (selected) {
self.imageView.transform = CGAffineTransformMakeScale(1.1, 1.1);
self.titleLabel.transform = CGAffineTransformMakeScale(1.1, 1.1);
self.titleLabel.font = [UIFont boldSystemFontOfSize:12];
} else {
self.imageView.transform = CGAffineTransformIdentity;
self.titleLabel.transform = CGAffineTransformIdentity;
self.titleLabel.font = [UIFont systemFontOfSize:12];
}
}];
}
位移動畫
// ZHTabBar.m
// 以動畫的方式布局所有button
- (void)layoutSubviewsAnimated:(BOOL)animated
{
// 計算每個tabBarButton的frame
CGFloat w = self.bounds.size.width;
CGFloat h = self.bounds.size.height;
CGFloat btnX = 0;
CGFloat btnW = w / self.buttons.count;
CGFloat minW = w / (self.buttons.count + 0.5);
ZHTabBarButton *lastView = nil;
for (ZHTabBarButton *subView in self.buttons) {
if (_style == ZHTabBarAnimationStyleTranslation) {
btnW = subView.isSelected ? minW * 1.5 : minW;
}
btnX = CGRectGetMaxX(lastView.frame);
// 被點擊的按鈕寬度變大,其他變小
if (animated) {
[UIView animateWithDuration:0.3 animations:^{
subView.frame = CGRectMake(btnX, 0, btnW, h);
}];
} else {
subView.frame = CGRectMake(btnX, 0, btnW, h);
}
lastView = subView;
}
}
// button點擊事件
- (void)buttonClick:(UIButton *)button
{
// 代理方法
if ([_delegate respondsToSelector:@selector(tabBar:didSelectedItemFrom:to:)]) {
[_delegate tabBar:self didSelectedItemFrom:self.selectedButton.tag to:button.tag];
}
_selectedButton.selected = NO;
button.selected = YES;
_selectedButton = button;
// 每次點擊按鈕卒茬,重新布局
[self layoutSubviewsAnimated:YES];
}
ZHTabBarButton.m
// 重寫來自定義布局
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat imageRatio = 0.7;
CGFloat imgX = 0;
CGFloat imgY = 0;
CGFloat imgW = CGRectGetWidth(self.frame);
CGFloat imgH = (self.isSelected || _isShowTitle) ? CGRectGetHeight(self.frame) * imageRatio : CGRectGetHeight(self.frame);
self.imageView.frame = CGRectMake(imgX, imgY, imgW, imgH);
CGFloat ttlY = CGRectGetHeight(self.frame) * imageRatio;
CGFloat ttlW = CGRectGetWidth(self.frame);
CGFloat ttlH = CGRectGetHeight(self.frame) * 0.2;
if (_isShowTitle) {
self.titleLabel.frame = CGRectMake(0, 0, ttlW, ttlH);
}
self.titleLabel.center = CGPointMake(ttlW/2.f, ttlY + ttlH/2.f);
// 顯隱動畫
[UIView animateWithDuration:0.3 animations:^{
self.titleLabel.alpha = _isShowTitle || self.isSelected;
}];
}
謝謝船老!