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

雖然現在主流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

github項目地址

WXWTabBarController.gif

另外,類似閑魚、QQ空間中間按鈕不和VC關聯也寫了個小demo:

該demo對應github地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容

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