iOS侧边栏

作者: 维子Vanessa | 来源:发表于2016-10-24 20:49 被阅读1028次

    有时候项目需求TabBar在侧边,不在底部,当需要的时候显示出来,不需要的时候隐藏

    基于这种需求,自定义一个侧边栏和UITabController

    效果.gif

    第一步:

    首先封装一个侧边栏的控件

    .h文件
    #import <UIKit/UIKit.h>
    
    @protocol LeftViewDelegate <NSObject>
    /**
     点击侧边栏按钮调用方法(必写)
    
     @param selectedIndex 按钮tag
     */
    @required
    - (void)didClickChildButton:(int)selectedIndex;
    
    @end
    
    @interface LeftView : UIView
    
    @property(nonatomic, strong) NSArray *itemArray;
    @property(nonatomic, strong) id <LeftViewDelegate>delegate;
    
    @end
    
    @interface TabButton : UIButton
    
    @end
    
    .m文件
    #import "LeftView.h"
    
    #define VIEW_WIDTH self.bounds.size.width
    #define VIEW_HEIGHT self.bounds.size.height
    
    @interface LeftView()
    
    @property(nonatomic, strong) UIButton *selectedButton;
    
    @end
    
    @implementation LeftView
    
    -(instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self setUp];
        }
        return self;
    }
    
    - (void)setUp
    {
        self.backgroundColor = [UIColor whiteColor];
    }
    
    - (void)setItemArray:(NSArray *)itemArray
    {
        _itemArray = itemArray;
        int n = 0;
        for (NSDictionary *dict in itemArray) {
            TabButton *button = [TabButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:dict[@"title"] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:dict[@"image"]] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:dict[@"selectImage"]] forState:UIControlStateSelected];
            button.tag = 999 + n;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            // 默认第一个按钮点击,跟tabbarController默认选中的控制器index一致
            if (n == 0) {// 0
                self.selectedButton = button;
                self.selectedButton.selected = YES;
            }
            n ++;
        }
    }
    
    - (void)buttonClick:(UIButton *)button
    {
        int tag = (int)button.tag - 999;
        NSLog(@"点击了%d个按钮",tag);
        if ([self.delegate respondsToSelector:@selector(didClickChildButton:)]) {
            [self.delegate didClickChildButton:tag];
            self.selectedButton.selected = NO;
            self.selectedButton = button;
            self.selectedButton.selected = YES;
        }
    }
    
    -(void)layoutSubviews
    {
        CGFloat height = [UIScreen mainScreen].bounds.size.height / 4;
        
        for (UIView *child in self.subviews) {
            Class class = NSClassFromString(@"UIButton");
            if ([child isKindOfClass:class]) {
                int tag = (int)child.tag - 999;
                child.frame = CGRectMake(0, height * tag, VIEW_WIDTH, height);
            }
        }
    }
    
    @end
    
    #pragma mark - 自定义tabBar按钮
    @implementation TabButton
    
    - (void)layoutSubviews{
        [super layoutSubviews];
        
        self.imageView.frame = CGRectMake(0, VIEW_HEIGHT * 0.1, VIEW_WIDTH, VIEW_HEIGHT * 0.5);
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        self.titleLabel.frame = CGRectMake(0, VIEW_HEIGHT * 0.6, VIEW_WIDTH, VIEW_HEIGHT * 0.2);
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    
    @end
    

    第二步:自定义UITabController

    .m文件
    #import "MainTabBarController.h"
    #import "OneViewController.h"
    #import "TwoViewController.h"
    #import "ThreeViewController.h"
    #import "FourViewController.h"
    #import "LeftView.h"
    
    // 侧边栏的宽度
    #define LEFT_WIDTH 100
    
    @interface MainTabBarController ()<LeftViewDelegate>
    
    @property(nonatomic, strong) LeftView *lefeView;
    @property(nonatomic, strong) UIView *bgView;
    @property (assign, nonatomic,getter=isHidden)  BOOL hidden;
    // tabBar 的标题+图片字典数组
    @property(nonatomic, strong) NSMutableArray *tabItems;
    
    @end
    
    @implementation MainTabBarController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        
        // init child vc
        NSMutableArray *array = [NSMutableArray array];
        OneViewController *onevc = [[OneViewController alloc] init];
        TwoViewController *twovc = [[TwoViewController alloc] init];
        ThreeViewController *threevc = [[ThreeViewController alloc] init];
        FourViewController *fourvc = [[FourViewController alloc] init];
        
        [self setUpChildViewController:onevc array:array title:@"话题" imageName:@"tabbar_topic" selectImageName:@"tabbar_topic_selected"];
        [self setUpChildViewController:twovc array:array title:@"材料" imageName:@"tabbar_material" selectImageName:@"tabbar_material_selected"];
        [self setUpChildViewController:threevc array:array title:@"表单" imageName:@"tabbar_form" selectImageName:@"tabbar_form_selected"];
        [self setUpChildViewController:fourvc array:array title:@"更多" imageName:@"tabbar_more" selectImageName:@"tabbar_more_selected"];
        
        self.viewControllers = array;
        self.selectedIndex = 0;
        self.hidden = YES;
        
        // ori tabbar set nil ......
        [self setValue:nil forKeyPath:@"tabBar"];
        
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    }
    
    - (void)setUpChildViewController:(UIViewController *)viewController array:(NSMutableArray *)array title:(NSString *)title imageName:(NSString *)imageName selectImageName:(NSString *)selectImageName
    {
        UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:viewController];
        viewController.view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"item.png"] style:UIBarButtonItemStylePlain target:self action:@selector(tabHiddenOrShow)];
        [array addObject:navVC];
        
        NSDictionary *dict = @{@"title":title,
                               @"image":imageName,
                               @"selectImage":selectImageName
                               };
        [self.tabItems addObject:dict];
    }
    
    - (void)tabHiddenOrShow
    {
        [self.tabBarController.tabBar setHidden:YES];
        self.hidden = !self.isHidden;
        
        if (self.lefeView == nil) {
            self.lefeView = [[LeftView alloc] initWithFrame:CGRectMake(-LEFT_WIDTH, 0, LEFT_WIDTH, [UIScreen mainScreen].bounds.size.height)];
            self.lefeView.delegate = self;
            self.lefeView.itemArray = self.tabItems;
            [[UIApplication sharedApplication].keyWindow addSubview:self.lefeView];
        }
        if (self.bgView == nil) {
            self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
            self.bgView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.5];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
            [self.bgView addGestureRecognizer:tap];
        }
        
        CGRect leftFrame = self.lefeView.frame;
        if (self.isHidden == YES) {
            leftFrame.origin.x = -LEFT_WIDTH;
            [self.bgView removeFromSuperview];
        } else {
            [[UIApplication sharedApplication].keyWindow insertSubview:self.bgView belowSubview:self.lefeView];
            leftFrame.origin.x = 0;
        }
        [UIView animateWithDuration:0.5 animations:^{
            self.lefeView.frame = leftFrame;
            [self.view setNeedsLayout];
        }];
    }
    
    - (void)tapClick:(UITapGestureRecognizer *)tap
    {
        [self tabHiddenOrShow];
    }
    
    
    #pragma mark - LeftViewDelegate
    -(void)didClickChildButton:(int)selectedIndex
    {
        self.selectedIndex = selectedIndex;
        [self tabHiddenOrShow];
    }
    
    
    #pragma mark - set & get
    -(NSMutableArray *)tabItems
    {
        if (_tabItems == nil) {
            _tabItems = [NSMutableArray array];
        }
        return _tabItems;
    }
    
    @end
    

    在你需要添加UITabController的地方使用

    我这里在APPDELAGE里使用到的

    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        
        MainTabBarController *mainVC = [[MainTabBarController alloc]init];
        self.window.rootViewController = mainVC;
        
        [self.window makeKeyAndVisible];
    

    详细代码请看:
    https://github.com/Vanessa1990/SideBar

    相关文章

      网友评论

      • 通_552b:为什么我按笔者的做法底部会有Tab bar view 出现的呢? 请问怎样隐藏

      本文标题:iOS侧边栏

      本文链接:https://www.haomeiwen.com/subject/lrgluttx.html