雖然現在主流app很少做這種設計,但是我確實碰到了,還不止一次,上次隨便寫寫沒怎么總結,這次稍微整理了下。和閑魚、qq空間不同的是需求要求中間item對應了一個VC,而閑魚、QQ空間是中間item對應一個按鈕。不足之處大佬們多多批評指正。
樣式
gif5新文件.gif
思路
上移中間tabBarItem的范圍,同時擴大它的點擊范圍,只有中間的才會擴大,item為偶數的話是正常顯示的。實現代碼
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01)
{
return nil;
}
if (self.clipsToBounds && ![self pointInside:point withEvent:event]) {
return nil;
}
if ([self pointInside:point withEvent:event])
{
return [self mmHitTest:point withEvent:event];
}
else
{
CGFloat tabBarItemWidth = self.bounds.size.width/self.items.count;
CGFloat left = self.center.x - tabBarItemWidth/2;
CGFloat right = self.center.x + tabBarItemWidth/2;
if (point.x < right &&
point.x > left)
{//當點擊的point的x坐標是中間item范圍內,才去修正落點
CGPoint otherPoint = CGPointMake(point.x, point.y + self.effectAreaY);
return [self mmHitTest:otherPoint withEvent:event];
}
}
return nil;
}
- (UIView *)mmHitTest:(CGPoint)point withEvent:(UIEvent *)event
{
for (UIView *subview in [self.subviews reverseObjectEnumerator])
{
CGPoint convertedPoint = [subview convertPoint:point fromView:self];
UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
if (hitTestView) {
return hitTestView;
}
}
return nil;
}
更改TabBar樣式,選中某個TabBarItem添加動畫
- (void)uiSetting {
// 更換tabBar
CustomTabBar *myTabBar = [[CustomTabBar alloc] init];
myTabBar.effectAreaY = 35;
[self setValue:myTabBar forKey:@"tabBar"];
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for (NSInteger i = 0;i < self.tabBarViewControllers.count; i++) {
NSString *imageNormal = [NSString stringWithFormat:@"%@",_tabBarItemsAttributes[i][WXWTabBarItemImage]];
NSString *imageSelected = [NSString stringWithFormat:@"%@",_tabBarItemsAttributes[i][WXWTabBarItemSelectedImage]];
UIViewController *vc = self.tabBarViewControllers[i];
[vc setTitle:_tabBarItemsAttributes[i][WXWTabBarItemTitle]];
vc.tabBarItem.image = [[UIImage imageNamed:imageNormal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
vc.tabBarItem.selectedImage = [[UIImage imageNamed:imageSelected] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
NSValue *insetsValue = _tabBarItemsAttributes[i][WXWTabBarItemImageInsets];
UIEdgeInsets insets = [insetsValue UIEdgeInsetsValue];
[vc.tabBarItem setImageInsets:insets];//修改圖片偏移量,上下,左右必須為相反數,否則圖片會被壓縮
NSValue *offsetValue = _tabBarItemsAttributes[i][WXWTabBarItemTitlePositionAdjustment];
UIOffset offset = [offsetValue UIOffsetValue];
[vc.tabBarItem setTitlePositionAdjustment:offset];//修改文字偏移量
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
nav.title = _tabBarItemsAttributes[i][WXWTabBarItemTitle];
[mArr addObject:nav];
}
self.viewControllers = mArr;
self.selectedIndex = 0;
self.mItemArray = nil;
for (UIView *btn in self.tabBar.subviews) {
if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
[self.mItemArray addObject:btn];
}
}
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
NSInteger index = [self.tabBar.items indexOfObject:item];
if (index != self.indexFlag) {
UIButton *btn = self.mItemArray[index];
UIView *animationView = [btn wxw_tabImageView];
if (index == 1 && self.selectedAnimation) {
[self addScaleAnimationOnView:animationView repeatCount:1];
} else if (index != 1 && self.selectedAnimation) {
[self addRotateAnimationOnView:animationView];
}
[self.tabBar bringSubviewToFront:self.mItemArray[self.indexFlag]];
self.indexFlag = index;
}
}
//縮放動畫
- (void)addScaleAnimationOnView:(UIView *)animationView repeatCount:(float)repeatCount {
//需要實現的幀動畫,這里根據需求自定義
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.keyPath = @"transform.scale";
animation.values = @[@1.0,@1.3,@0.9,@1.15,@0.95,@1.02,@1.0];
animation.duration = 1;
animation.repeatCount = repeatCount;
animation.calculationMode = kCAAnimationCubic;
[animationView.layer addAnimation:animation forKey:nil];
}
//旋轉Y動畫
- (void)addRotateAnimationOnView:(UIView *)animationView {
// 針對旋轉動畫,需要將旋轉軸向屏幕外側平移,最大圖片寬度的一半
// 否則背景與按鈕圖片處于同一層次,當按鈕圖片旋轉時,轉軸就在背景圖上,動畫時會有一部分在背景圖之下。
// 動畫結束后復位
animationView.layer.zPosition = 65.f / 2;
[UIView animateWithDuration:0.32 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
animationView.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
} completion:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.70 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
animationView.layer.transform = CATransform3DMakeRotation(2 * M_PI, 0, 1, 0);
} completion:nil];
});
}
使用
新建一個對象,用于更改Tabbar的樣式配置,在delegate的didFinishLaunchingWithOptions方法中把自定義的TabBarController設置為根視圖
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
WXWTabBarControllerConfig *tabBarControllerConfig = [[WXWTabBarControllerConfig alloc] init];
CustomTabBarController *tabBarController = tabBarControllerConfig.tabBarController;
self.window.rootViewController = tabBarController;
return YES;
}
樣式可以根據自己的需求調整,具體實現如下
#import <Foundation/Foundation.h>
#import "CustomTabBarController.h"
@interface WXWTabBarControllerConfig : NSObject
@property (nonatomic, readonly, strong) CustomTabBarController *tabBarController;
@end
#import "WXWTabBarControllerConfig.h"
//十六進制顏色
#define ColorFromHexValue(hexValue) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:1.0]
@interface WXWTabBarControllerConfig()
@property (strong, readwrite, nonatomic) CustomTabBarController *tabBarController;
@end
#import "FirstViewController.h"
#import "SecondViewController.h"
#import "ThirdViewController.h"
@implementation WXWTabBarControllerConfig
/**
* lazy load tabBarController
*
* @return WXWTabBarController
*/
- (CustomTabBarController *)tabBarController {
if (_tabBarController == nil) {
/**
* 以下兩行代碼目的在于手動設置讓TabBarItem只顯示圖標,不顯示文字,并讓圖標垂直居中。
* 等效于在 `-tabBarItemsAttributesForController` 方法中不傳 `WXWTabBarItemTitle` 字段。
* 更推薦后一種做法。
*/
UIEdgeInsets imageInsets = UIEdgeInsetsZero;//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
UIOffset titlePositionAdjustment = UIOffsetZero;//UIOffsetMake(0, MAXFLOAT);
CustomTabBarController *tabBarController = [CustomTabBarController tabBarControllerWithViewControllers:self.viewControllers
tabBarItemsAttributes:self.tabBarItemsAttributesForController
imageInsets:imageInsets
titlePositionAdjustment:titlePositionAdjustment
];
[self customizeTabBarAppearance:tabBarController];
tabBarController.selectedAnimation = YES; //選中動畫關閉
_tabBarController = tabBarController;
}
return _tabBarController;
}
- (NSArray *)viewControllers {
FirstViewController *firstViewController = [[FirstViewController alloc] init];
SecondViewController *secondViewController = [[SecondViewController alloc] init];
ThirdViewController *thirdViewController = [[ThirdViewController alloc] init];
NSArray *viewControllers = @[
firstViewController,
secondViewController,
thirdViewController
];
return viewControllers;
}
- (NSArray *)tabBarItemsAttributesForController {
NSDictionary *firstTabBarItemsAttributes = @{
WXWTabBarItemTitle : @"加速",
WXWTabBarItemImage : @"加速未選中", /* NSString and UIImage are supported*/
WXWTabBarItemSelectedImage : @"加速選中", /* NSString and UIImage are supported*/
WXWTabBarItemImageInsets: [NSValue valueWithUIEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)],
WXWTabBarItemTitlePositionAdjustment: [NSValue valueWithUIOffset:UIOffsetMake(0, 0)]
};
NSDictionary *secondTabBarItemsAttributes = @{
WXWTabBarItemTitle : @"",
WXWTabBarItemImage : @"游戲列表未選中",
WXWTabBarItemSelectedImage : @"游戲列表選中",
WXWTabBarItemImageInsets: [NSValue valueWithUIEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)],
WXWTabBarItemTitlePositionAdjustment: [NSValue valueWithUIOffset:UIOffsetMake(0, 0)]
};
NSDictionary *thirdTabBarItemsAttributes = @{
WXWTabBarItemTitle : @"我的",
WXWTabBarItemImage : @"我的未選中",
WXWTabBarItemSelectedImage : @"我的選中",
WXWTabBarItemImageInsets: [NSValue valueWithUIEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)],
WXWTabBarItemTitlePositionAdjustment: [NSValue valueWithUIOffset:UIOffsetMake(0, 0)]
};
NSArray *tabBarItemsAttributes = @[
firstTabBarItemsAttributes,
secondTabBarItemsAttributes,
thirdTabBarItemsAttributes,
];
return tabBarItemsAttributes;
}
/**
* 更多TabBar自定義設置:比如:tabBarItem 的選中和不選中文字和背景圖片屬性、tabbar 背景圖片屬性等等
*/
- (void)customizeTabBarAppearance:(CustomTabBarController *)tabBarController {
// set the text color for unselected state
// 普通狀態下的文字屬性
NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
normalAttrs[NSForegroundColorAttributeName] = ColorFromHexValue(0x8e8e8e);
// set the text color for selected state
// 選中狀態下的文字屬性
NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
selectedAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
// set the text Attributes
// 設置文字屬性
UITabBarItem *tabBar = [UITabBarItem appearance];
[tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
[tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
[[UITabBar appearance] setBackgroundColor:ColorFromHexValue(0x262626)];
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
}
+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize {
CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize);
UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
[image drawInRect:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
if (!color || size.width <= 0 || size.height <= 0) return nil;
CGRect rect = CGRectMake(0.0f, 0.0f, size.width + 1, size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
WXWTabBarController.gif
另外,類似閑魚、QQ空間中間按鈕不和VC關聯也寫了個小demo: