iOS開發之自定義UITabBarController-模態出半透明的控制器

weixin_34337265發表於2017-03-21
3018792-d41579b2c0cc689f.gif
自定義tabBar並modal出半透明的控制器的view.gif

前言

現在很多app,尤其一些直播的app,都在做如上的tabBar點選效果,點選兩邊的按鈕是蘋果預設的切換方式,點選中間按鈕,是模態出一個新控制器的view,這裡主要涉及到自定義UITabBarController,你可能還看到modal出的新控制器的view是半透明的,在顯示自己view的同時也可以看到原先控制器的檢視,這裡主要用了控制器的一個modalPresentationStyle屬性來設定,最近看到很多直播app的如上效果,於是想著自己封裝實現一下,放出來,供大家參考。

正文

自定義UITabBarController:

自定義UITabBarController的實現原理其實很簡單,就是隱藏蘋果自帶的tabBar,使用自定義UIView代替;然後自定義Button加在自定義的tabBar的view上;最後將自定義的button 與UITabBarController的子viewController一一對應。而自定義的button需要使上面顯示按鈕圖片,下面是文字Label,實現這些的重點是計算Button的imageView和Label的寬度和X座標值。

下面是具體的實現程式碼:

CustomTabBar:繼承自UIView,充當tabBar

#import <UIKit/UIKit.h>

@class CustomTabBar;

@protocol CustomTabBarDelegate <NSObject>

- (void)myTabbar:(CustomTabBar *)tabbar btnClicked:(NSInteger)index;

@end

@interface CustomTabBar : UIView
/** 初始化方法
 引數1: 位置大小
 引數2: 內部按鈕個數
 */
- (instancetype)initWithFrame:(CGRect)frame itemCount:(NSInteger)itemCount;

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

@end

#import "CustomTabBar.h"
#import "CustomTabBarItemButton.h"

@interface CustomTabBar ()

@property (nonatomic,assign) NSInteger itemCount;// 子控制器個數
@property (nonatomic,assign) UIButton *previousBtn;// 前一個被點選的按鈕

@end

@implementation CustomTabBar

- (instancetype)initWithFrame:(CGRect)frame itemCount:(NSInteger)itemCount
{
    if (self = [super initWithFrame:frame]) {
        // 儲存按鈕個數
        _itemCount = itemCount;
        
        // 設定背景顏色
        self.backgroundColor = [UIColor whiteColor];
        
        // 建立按鈕
        [self createBtn];
    }
    
    return self;
}

#pragma mark 建立tabBarItem
- (void)createBtn {
    // 迴圈建立按鈕
    
    // 計算按鈕的寬高
    CGFloat w = self.bounds.size.width / (self.itemCount+1);
    CGFloat h = self.bounds.size.height;
    NSArray *selectedImgArr = @[@"tab_live_p",@"tab_launch",@"tab_me_p"];
    NSArray *normalImgarr = @[@"tab_live",@"tab_launch",@"tab_me"];
    NSArray *titleArr = @[@"首頁",@"",@"我"];
    for (int i = 0; i < self.itemCount+1; i ++) {
        
        if(0 == i){
            CustomTabBarItemButton *btn = [[CustomTabBarItemButton alloc] initWithFrame:CGRectMake(i * w, 0, w, h) imgName:normalImgarr[i] selectedImgName:selectedImgArr[i] titleColor:[UIColor colorWithRed:34/255.0 green:209/255.0 blue:188/255.0 alpha:1.0] title:titleArr[i]];
            btn.tag = 0;
            // 新增按鈕的點選事件
            [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:btn];
            [self btnClicked:btn];
        }
        if (1 == i) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake((self.frame.size.width-87)/2, -37, 87, 87);
            [btn setImage:[UIImage imageNamed:selectedImgArr[i]] forState:UIControlStateNormal];
            btn.tag = 2;
            // 新增按鈕的點選事件
            [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:btn];
        }
        
        if(2 == i){
            CustomTabBarItemButton *btn = [[CustomTabBarItemButton alloc] initWithFrame:CGRectMake(i * w, 0, w, h) imgName:normalImgarr[i] selectedImgName:selectedImgArr[i] titleColor:[UIColor colorWithRed:34/255.0 green:209/255.0 blue:188/255.0 alpha:1.0] title:titleArr[i]];
            btn.tag = 1;
            // 新增按鈕的點選事件
            [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:btn];
        }

        
    }
}

#pragma mark tabBarItem被點選讓代理使UITabBarController的子控制器與其對應
- (void)btnClicked:(UIButton *)btn {

    if (0 == btn.tag||1 == btn.tag) {
        _previousBtn.selected = NO;
        btn.selected = YES;
        
        _previousBtn = btn;
        
    }
    if ([_delegate respondsToSelector:@selector(myTabbar:btnClicked:)]) {
        [_delegate myTabbar:self btnClicked:btn.tag];
    }
}

#pragma mark 當按鈕超過了父檢視範圍,點選是沒有反應的。因為訊息的傳遞是從最下層的父檢視開始呼叫hittest方法。當存在view時才會傳遞對應的event,現在點選了父檢視以外的範圍,自然返回的是nil。所以當子檢視(比如按鈕btn)因為一些原因超出了父檢視範圍,就要重寫hittest方法,讓其返回對應的子檢視,來接收事件。
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        
        UIButton *btn = (UIButton *)[self viewWithTag:2];
        CGPoint tempoint = [btn convertPoint:point fromView:self];
        //判斷給定的點是否被一個CGRect包含,可以用CGRectContainsPoint函式
        if (CGRectContainsPoint(btn.bounds, tempoint))
        {
            view = btn;
        }
    }
    return view;
}

CustomTabBarItemButton:繼承自UIButton,充當tabBarItem

#import <UIKit/UIKit.h>

@interface CustomTabBarItemButton : UIButton

- (instancetype)initWithFrame:(CGRect)frame imgName:(NSString *)imgName selectedImgName:(NSString *)selectedImgName titleColor:(UIColor *)color title:(NSString *)title;

@end


#import "CustomTabBarItemButton.h"

@implementation CustomTabBarItemButton

- (instancetype)initWithFrame:(CGRect)frame imgName:(NSString *)imgName selectedImgName:(NSString *)selectedImgName titleColor:(UIColor *)color title:(NSString *)title
{
    if (self = [super initWithFrame:frame]) {
        // 設定文字,字號,圖片,文字顏色
        [self setTitle:title forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:12];
        [self setTitleColor:color forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
        [self setImage:[UIImage imageNamed:selectedImgName] forState:UIControlStateSelected];
        
        // 設定文字和圖片的位置
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return self;
}

#pragma mark 設定高亮狀態的方法
// 在這個方法裡面,系統會預設給按鈕設定高亮狀態的的情景
// 覆蓋此方法,會使按鈕的高亮狀態不呈現任何情景
- (void)setHighlighted:(BOOL)highlighted {}

#pragma mark 設定文字frame
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    // 標籤檢視高度佔按鈕高度的1/3
    return CGRectMake(0, self.bounds.size.height / 3 * 2, self.bounds.size.width, self.bounds.size.height / 3);
}

#pragma mark 設定圖片frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    // 圖片檢視高度佔按鈕高度的2/3
    return CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height / 3 * 2);
}


@end

MyTabBarViewController:繼承自UITabBarController

#import "MyTabBarViewController.h"
#import "CustomTabBar.h"
#import "HomeViewController.h"
#import "LiveViewController.h"
#import "MYCenterViewController.h"

#import "AppDelegate.h"

@interface MyTabBarViewController ()<CustomTabBarDelegate>

@end

@implementation MyTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.設定所有子控制器
    [self addChildViewControllers];
    
    // 2.建立自定義的tabbar
    [self createCustomTabbar];
}

#pragma mark 設定所有的子控制器
- (void)addChildViewControllers {
    
    HomeViewController *homeVC = [[HomeViewController alloc] init];
    MYCenterViewController *myCenterVC = [[MYCenterViewController alloc] init];
    
    // 設定子控制器
    self.viewControllers = @[homeVC, myCenterVC];
}

#pragma mark 隱藏系統自帶的tabBar,建立自定義的tabBar
- (void)createCustomTabbar {
    // 1.隱藏系統tabbar
    self.tabBar.hidden = YES;
    
    // 2.建立自定義的tabbar
    CustomTabBar *myTabbar = [[CustomTabBar alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50) itemCount:self.viewControllers.count];
    myTabbar.delegate = self;
    [self.view addSubview:myTabbar];
}

#pragma mark CustomTabBarDelegate方法,tabBarItem被點選
- (void)myTabbar:(CustomTabBar *)tabbar btnClicked:(NSInteger)index
{
    if (2 == index) {
        /*
         *當點選中間的按鈕,modal出LiveViewController的檢視,並且不覆蓋原先檢視
         */
        //iOS 8.0之後的方法
        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0){
            
            LiveViewController *liveVC = [[LiveViewController alloc] init];
            //設定modal出的檢視view的透明度
            liveVC.view.alpha = 0.9;
            //此模式必須設定,否則會覆蓋原先檢視,看不到原先檢視的view
            liveVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [self presentViewController:liveVC animated:YES completion:nil];
            
        }else{
            //在iOS7或更低需要設定你的window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext
            AppDelegate *appdelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
            LiveViewController *liveVC = [[LiveViewController alloc] init];
            liveVC.view.alpha = 0.9;
            appdelegate.window.rootViewController.modalPresentationStyle=UIModalPresentationCurrentContext;
            [appdelegate.window.rootViewController presentViewController:liveVC animated:YES completion:nil];
        }
    }else{
        //設定選擇的子控制器與點選的按鈕相對應
        self.selectedIndex = index;
    }
}
@end
modal出的新控制器的半透明的view:

模態出一個半透明的檢視, 在目標檢視中設定背景顏色然後發現模態動作結束後變成了黑色或者不是半透明的顏色。在iOS8之後只需要為要present的控制器的modalPresentationStyle屬性設定一個最新的值UIModalPresentationOverCurrentContext就可以解決這種需求。
然而這個屬性是iOS 8才出來的,所以針對iOS 7或更低的系統,需要設定window的根控制器的modalPresentationStyle為UIModalPresentationCurrentContext。
程式碼如下:

if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0){
            LiveViewController *liveVC = [[LiveViewController alloc] init];
            //設定modal出的檢視view的透明度
            liveVC.view.alpha = 0.9;
            //此模式必須設定,否則會覆蓋原先檢視,看不到原先檢視的view
            liveVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [self presentViewController:liveVC animated:YES completion:nil];
            
        }else{
            //在iOS7或更低需要設定你的window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext
            AppDelegate *appdelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
            LiveViewController *liveVC = [[LiveViewController alloc] init];
            liveVC.view.alpha = 0.9;
            appdelegate.window.rootViewController.modalPresentationStyle=UIModalPresentationCurrentContext;
            [appdelegate.window.rootViewController presentViewController:liveVC animated:YES completion:nil];
        }

原始碼已上傳至fenglinyunshi-git,歡迎下載,並提出寶貴意見。

相關文章