iOS開發(fā)之自定義TabBarController-present(模態(tài))出控制器

點擊TabBar present出控制器.gif

?如上圖這種點擊TabBar中間Button時present(模態(tài))出控制器,而點擊TabBar其它的Button則是蘋果默認的直接切換視圖的方式吼驶,現(xiàn)在很多APP都在使用析恢,特別是直播APP,基本都把直播端模塊放在這殴泰,最近在仿喵播時正好做到這挚歧,?就想在網(wǎng)上找現(xiàn)成的框架扛稽,結(jié)果一直沒找到能滿足這種需求的框架,就自己動手寫了一個滑负,沒有仔細打磨算不上框架在张,但絕對簡單好用用含!

自定義TabBarController實現(xiàn)原理很簡單,無非是用自定義的Button替換掉蘋果自帶的TabBar上的Button帮匾,一般目的是想TabBar上方顯示按鈕圖片啄骇,下面是文字;也就是每個Button下面有一個Label瘟斜。實現(xiàn)這些的重點是計算ButtonLabel的寬度和X坐標值缸夹。

下面是JFTabBarController代碼實現(xiàn):

1、 新建三個類:

  • JFTabBar繼承自UIview
  • JFTabBarButton繼承自UIButton
  • JFTabBarController繼承自UITabBarController

2螺句、具體代碼:

  • JFTabBar.h
#import <UIKit/UIKit.h>

@class JFTabBar;

@protocol JFTabBarDelegate <NSObject>

@optional

- (void)tabBar:(JFTabBar *)tabBar didSelectedButtonFrom:(int)from to:(int)to;

@end

@interface JFTabBar : UIView

- (void)addTabBarButtonWithItem:(UITabBarItem *)item;

- (void)customTheMiddleButtonWithImageName:(NSString *)imageName;

@property (nonatomic, weak) id<JFTabBarDelegate> delegate;

@end
  • JFTabBar.m
#import "JFTabBar.h"

#import "JFTabBarButton.h"

//中間按鈕被點擊的通知
//此通知需要在JFTabBarController中監(jiān)聽
static NSString * const JFTabBarClickMiddleButtonDidNotification = @"JFTabBarClickMiddleButtonDidNotification";

@interface JFTabBar(){
    CGFloat _buttonW;
}

@property (nonatomic, weak) JFTabBarButton *selectedButton;

@property (nonatomic, strong) UIButton *middleButton;

@end

@implementation JFTabBar

- (void)addTabBarButtonWithItem:(UITabBarItem *)item {
    JFTabBarButton *button = [[JFTabBarButton alloc] init];
    [self addSubview:button];
    button.item = item;
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}

- (void)buttonClick:(JFTabBarButton *)button {
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:(int)self.selectedButton.tag to:(int)button.tag];
    }
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
}

/**
 *  self.subviews.count + 1 這里加1是將button的width按三個button計算明未,實際上是兩個button(如果不想present就不需要加1,下面兩個if判斷也可以去掉)
 *  兩個if判斷:1壹蔓、是將button的x坐標按三個button計算;2猫态、tag值回歸正常,不然無法正常切換控制器
 *  如你需要添加更多的控制器,這里就需要你自己計算榨为,然后修改以上兩點
 */
- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat buttonH = self.frame.size.height;
    _buttonW = self.frame.size.width / (self.subviews.count + 1);
    CGFloat buttonY = 0;
    for (int index = 0; index < self.subviews.count; index++) {
        JFTabBarButton *button = self.subviews[index];
        if (index == 1) index ++;
        CGFloat buttonX = index * _buttonW;
        button.frame = CGRectMake(buttonX, buttonY, _buttonW, buttonH);
        if (index == 2) index --;
        button.tag = index;
    }
    [self customTheMiddleButtonWithImageName:@"toolbar_live"];
}

//自定義中間button按鈕
- (void)customTheMiddleButtonWithImageName:(NSString *)imageName {
//  將Button居中
    CGFloat middleButtonX = self.center.x - _buttonW / 2;
    _middleButton = [[UIButton alloc] initWithFrame:CGRectMake(middleButtonX, 0, _buttonW, self.frame.size.height)];
    [_middleButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [_middleButton addTarget:self action:@selector(didClickedMiddleButton:) forControlEvents:UIControlEventTouchDown];
    [self addSubview:_middleButton];
}

- (void)didClickedMiddleButton:(UIButton *)sender {
    //注冊中間button被點擊通知
    [[NSNotificationCenter defaultCenter] postNotificationName:JFTabBarClickMiddleButtonDidNotification object:self];
}
@end
  • JFTabBarButton.h
#import <UIKit/UIKit.h>

@interface JFTabBarButton : UIButton

@property (nonatomic, strong) UITabBarItem *item;

@end
  • JFTabBarButton.m
static const double JFTabBarButtonImageRatio = 0.8;
#import "JFTabBarButton.h"

@implementation JFTabBarButton

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:11];
        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted {}

- (CGRect)imageRectForContentRect:(CGRect)contentRect{
    CGFloat imageW = contentRect.size.width;
    CGFloat imageH = contentRect.size.height * JFTabBarButtonImageRatio;
    return CGRectMake(0, 10, imageW, imageH);
}

//Button下需要文字時打開
//- (CGRect)titleRectForContentRect:(CGRect)contentRect {
//    CGFloat titleY = contentRect.size.height * JFTabBarButtonImageRatio;
//    CGFloat titleW = contentRect.size.width;
//    CGFloat titleH = contentRect.size.height - titleY;
//    return CGRectMake(0, titleY, titleW, titleH);
//}

- (void)setItem:(UITabBarItem *)item {
    _item = item;
    //Button下需要文字時打開
//    [item addObserver:self forKeyPath:@"title" options:0 context:nil];
    [item addObserver:self forKeyPath:@"image" options:0 context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:0 context:nil];
    
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
}

- (void)dealloc {
    //Button下需要文字時打開
//    [self.item removeObserver:self forKeyPath:@"title"];
    [self.item removeObserver:self forKeyPath:@"image"];
    [self.item removeObserver:self forKeyPath:@"selectedImage"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//    [self setTitle:self.item.title forState:UIControlStateSelected];
//    [self setTitle:self.item.title forState:UIControlStateNormal];
    [self setImage:self.item.image forState:UIControlStateNormal];
    [self setImage:self.item.selectedImage forState:UIControlStateSelected];
}

@end
  • JFTabBarController.h

- (void)addAllChildViewControllers中添加除中間那個你需要present(模態(tài))出的控制器

#import <UIKit/UIKit.h>

extern NSString * const JFTabBarClickMiddleButtonDidNotification;

@interface JFTabBarController : UITabBarController

@end
  • JFTabBarController.m
#import "JFTabBarController.h"

#import "JFTabBar.h"
#import "JFDisplayViewController.h"
#import "JFMeViewController.h"
#import "JFLiveViewController.h"

@interface JFTabBarController ()<JFTabBarDelegate>

@property (nonatomic, weak) JFTabBar *customTabBar;

@end

@implementation JFTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customTabBarUI];
//  添加子控制器
    [self addAllChildViewControllers];

//  監(jiān)聽中間按鈕點擊事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentLiveController) name:@"JFTabBarClickMiddleButtonDidNotification" object:nil];
}
//  移除原生的TabBar
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    for (UIView *childView in self.tabBar.subviews) {
        if ([childView isKindOfClass:[UIControl class]]) {
            [childView removeFromSuperview];
        }
    }
}

- (void)customTabBarUI {
    JFTabBar *customTabBar = [[JFTabBar alloc] init];
    customTabBar.frame = self.tabBar.bounds;
    customTabBar.delegate = self;
    [self.tabBar addSubview:customTabBar];
    self.customTabBar = customTabBar;
}

- (void)tabBar:(JFTabBar *)tabBar didSelectedButtonFrom:(int)from to:(int)to{
    self.selectedIndex = to;
}

//   下面換成你自己需要添加的控制器就好,只添加除中間需要present(模態(tài))出的控制器锅睛。
- (void)addAllChildViewControllers {
    JFDisplayViewController *displayVC = [[JFDisplayViewController alloc] init];
    [self addChildViewController:displayVC title:@"視頻" imageName:@"toolbar_home" selectedImageName:@"toolbar_home_sel"];
    JFMeViewController *meVC = [[JFMeViewController alloc] init];
    [self addChildViewController:meVC title:@"個人" imageName:@"toolbar_me" selectedImageName:@"toolbar_me_sel"];
}

- (void)addChildViewController:(UIViewController *)childViewController title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName {
    childViewController.title = title;
    childViewController.tabBarItem.image = [UIImage imageNamed:imageName];
    childViewController.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:childViewController];
    [self addChildViewController:navigationController];
    [self.customTabBar addTabBarButtonWithItem:childViewController.tabBarItem];
}

//接收到點擊中間按鈕的通知,present(模態(tài))出控制器
- (void)presentLiveController {
    JFLiveViewController *jfLiveVC = [[JFLiveViewController alloc] init];
    [self presentViewController:jfLiveVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//  移除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

說了這么多义辕,如果你也只是需要三個控制器虾标,其實你只需要做這些:
1、下載JFTabBarController源碼灌砖,解壓將JFTabBarController文件夾中文件直接拖入你的xcode項目工程中璧函。
2、在AppDelegate.m文件中JFTabBarController設(shè)為window的根控制器基显。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[JFTabBarController alloc] init];
    [self.window makeKeyAndVisible];
    return YES;
}

3蘸吓、重寫JFTabBarcontroller.m文件中-(void)addAllChildViewControllers函數(shù),添加子控制器
4撩幽、JFTabBarClickMiddleButtonDidNotification通知库继,
重寫JFTabBarcontroller.m文件中- (void)presentLiveController方法。
你需要做的就這四步窜醉!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宪萄,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子榨惰,更是在濱河造成了極大的恐慌拜英,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件读串,死亡現(xiàn)場離奇詭異聊记,居然都是意外死亡撒妈,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門排监,熙熙樓的掌柜王于貴愁眉苦臉地迎上來狰右,“玉大人,你說我怎么就攤上這事舆床∑灏觯” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵挨队,是天一觀的道長谷暮。 經(jīng)常有香客問我,道長盛垦,這世上最難降的妖魔是什么湿弦? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮腾夯,結(jié)果婚禮上颊埃,老公的妹妹穿的比我還像新娘。我一直安慰自己蝶俱,他們只是感情好班利,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著榨呆,像睡著了一般罗标。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上积蜻,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天闯割,我揣著相機與錄音,去河邊找鬼竿拆。 笑死纽谒,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的如输。 我是一名探鬼主播鼓黔,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼不见!你這毒婦竟也來了澳化?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤稳吮,失蹤者是張志新(化名)和其女友劉穎缎谷,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體灶似,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡列林,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年瑞你,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片希痴。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡者甲,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出砌创,到底是詐尸還是另有隱情虏缸,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布嫩实,位于F島的核電站刽辙,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏甲献。R本人自食惡果不足惜宰缤,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望晃洒。 院中可真熱鬧撵溃,春花似錦、人聲如沸锥累。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽桶略。三九已至,卻和暖如春诲宇,著一層夾襖步出監(jiān)牢的瞬間际歼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工姑蓝, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鹅心,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓纺荧,卻偏偏與公主長得像旭愧,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子宙暇,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容