類似閑魚、QQ空間中間凸起的TabBar

雖然現(xiàn)在主流app很少做這種設(shè)計(jì),但是我確實(shí)碰到了,還不止一次,上次隨便寫寫沒怎么總結(jié),這次稍微整理了下。和閑魚、qq空間不同的是需求要求中間item對(duì)應(yīng)了一個(gè)VC,而閑魚、QQ空間是中間item對(duì)應(yīng)一個(gè)按鈕。不足之處大佬們多多批評(píng)指正。

樣式

gif5新文件.gif

思路

上移中間tabBarItem的范圍,同時(shí)擴(kuò)大它的點(diǎn)擊范圍,只有中間的才會(huì)擴(kuò)大,item為偶數(shù)的話是正常顯示的。實(shí)現(xiàn)代碼

- (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)
        {//當(dāng)點(diǎn)擊的point的x坐標(biāo)是中間item范圍內(nèi),才去修正落點(diǎn)
            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樣式,選中某個(gè)TabBarItem添加動(dòng)畫

- (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];//修改圖片偏移量,上下,左右必須為相反數(shù),否則圖片會(huì)被壓縮
        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;
    }
}

//縮放動(dòng)畫
- (void)addScaleAnimationOnView:(UIView *)animationView repeatCount:(float)repeatCount {
    //需要實(shí)現(xiàn)的幀動(dòng)畫,這里根據(jù)需求自定義
    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];
}

//旋轉(zhuǎn)Y動(dòng)畫
- (void)addRotateAnimationOnView:(UIView *)animationView {
    // 針對(duì)旋轉(zhuǎn)動(dòng)畫,需要將旋轉(zhuǎn)軸向屏幕外側(cè)平移,最大圖片寬度的一半
    // 否則背景與按鈕圖片處于同一層次,當(dāng)按鈕圖片旋轉(zhuǎn)時(shí),轉(zhuǎn)軸就在背景圖上,動(dòng)畫時(shí)會(huì)有一部分在背景圖之下。
    // 動(dòng)畫結(jié)束后復(fù)位
    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];
    });
}

使用

新建一個(gè)對(duì)象,用于更改Tabbar的樣式配置,在delegate的didFinishLaunchingWithOptions方法中把自定義的TabBarController設(shè)置為根視圖

- (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;
}

樣式可以根據(jù)自己的需求調(diào)整,具體實(shí)現(xiàn)如下

#import <Foundation/Foundation.h>
#import "CustomTabBarController.h"

@interface WXWTabBarControllerConfig : NSObject

@property (nonatomic, readonly, strong) CustomTabBarController *tabBarController;


@end
#import "WXWTabBarControllerConfig.h"
//十六進(jìn)制顏色
#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) {
        /**
         * 以下兩行代碼目的在于手動(dòng)設(shè)置讓TabBarItem只顯示圖標(biāo),不顯示文字,并讓圖標(biāo)垂直居中。
         * 等效于在 `-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; //選中動(dòng)畫關(guān)閉
        _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自定義設(shè)置:比如:tabBarItem 的選中和不選中文字和背景圖片屬性、tabbar 背景圖片屬性等等
 */
- (void)customizeTabBarAppearance:(CustomTabBarController *)tabBarController {

    // set the text color for unselected state
    // 普通狀態(tài)下的文字屬性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = ColorFromHexValue(0x8e8e8e);

    // set the text color for selected state
    // 選中狀態(tài)下的文字屬性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];

    // set the text Attributes
    // 設(shè)置文字屬性
    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

github項(xiàng)目地址

WXWTabBarController.gif

另外,類似閑魚、QQ空間中間按鈕不和VC關(guān)聯(lián)也寫了個(gè)小demo:

該demo對(duì)應(yīng)github地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 001 成功不是獲取財(cái)富,不是掌握權(quán)力而是贏得與自己的較量。 002 只要心中秉持著恒久不變的真理,就能屹立于動(dòng)蕩...
    拾樂者閱讀 336評(píng)論 0 3
  • 我們可以轉(zhuǎn)身,但是不必回頭,即使有一天,你發(fā)現(xiàn)自己走錯(cuò)了,你也應(yīng)該轉(zhuǎn)身,大步朝著對(duì)的方向去,而不是一直回頭怨自己錯(cuò)了。
    西瓜檸檬說閱讀 317評(píng)論 0 0
  • 文//千涼 我很喜歡波瀾不驚的河,就像閉著眼略帶倦容的孩子。 小祥子是我那日在河岸遇見的。那日我去河岸散心,發(fā)現(xiàn)了...
    SANGUO夢(mèng)想閱讀 988評(píng)論 0 7
  • 大家都知道早睡早起是良好的生活作息習(xí)慣,有利于自身身體健康,那它到底有哪些好處呢? 一、 別人都黑眼圈,就你容光煥...
    還淚閱讀 477評(píng)論 0 1

友情鏈接更多精彩內(nèi)容