大数据

iOS自定义tabBar

自定义Tabbar

首先看下 自定义的tabbar长什么样子,当然是根据需求定义的,废话不多说,直接捞干的。

8006469E-7F79-40E7-8F75-DAFC91D0A67C.png
#import "CSTabBar.h"
@interface CSTabBar ()
@property (nonatomic,strong) UIButton *plusButton;

@end


@implementation CSTabBar

//创建加号按钮
- (UIButton *)plusButton
{
    if (!_plusButton) {
        _plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_plusButton setImage:[UIImage imageNamed:@"plus50"] forState:(UIControlStateNormal)];
        [_plusButton setBackgroundImage:[UIImage imageNamed:@"yuan1"] forState:(UIControlStateNormal)];
        [_plusButton setBackgroundImage:[UIImage imageNamed:@"yuan1"] forState:(UIControlStateHighlighted)];
        [_plusButton addTarget:self action:@selector(plusButtonAction) forControlEvents:(UIControlEventTouchUpInside)];

        //背景图多大,button多大
         [_plusButton sizeToFit];

        [self addSubview:_plusButton];
    }

    return _plusButton;
}

//对item重新布局
- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height;

    CGFloat btnX = 0;
    CGFloat btnY = 0;
    CGFloat btnW = w / (self.items.count + 1);
    CGFloat btnH = self.bounds.size.height;

    int i = 0;

    for (UIView *tabBarButton in self.subviews) {

        // 判断下是否是UITabBarButton
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton" )]) {
            if (i == 2) {
                i = 3;
            }
             btnX = i * btnW;

            tabBarButton.frame = CGRectMake(btnX, btnY, btnW, btnH);

            i++;
        }

    }

    // 设置添加按钮的位置
    self.plusButton.center = CGPointMake(w * 0.5, h * 0.3);



}
//加号按钮的方法实现
- (void)plusButtonAction {
    CSPlusVC *plusVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"plusVC"];
    //kWindow为[UIApplication sharedApplication].keyWindow
    [kWindow.rootViewController presentViewController:plusVC animated:YES completion:nil];

}

创建tarBar

#import "CSTabBarController.h"
#import "CSTabBar.h"

@interface CSTabBarController ()

@end

@implementation CSTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setTabBar];

}

//创建tabBar
- (void)setTabBar {

    CSTabBar *tabBar = [[CSTabBar alloc] initWithFrame:self.tabBar.frame];

    tabBar.barTintColor = [UIColor colorWithRed:0.910 green:0.925 blue:0.933 alpha:1.000];

    tabBar.tintColor = [UIColor redColor];

    tabBar.translucent = NO;

 //必须用kvc 赋值才可以替换系统自带的tabBar
    [self setValue:tabBar forKeyPath:@"tabBar"];



}

看完后觉得简单么?那还等什么,自己试试吧!