自定义tabbar

效果图:

.h----->

#importtypedef void(^WelfareBlock)(void);

@interface MyTabbar : UITabBar

@property (copy , nonatomic) WelfareBlock block;

@end

.m----->

#import "MyTabbar.h"

#import "WelfareBarItemView.h"

@interface MyTabbar ()

@property (strong , nonatomic) WelfareBarItemView * welfareBarItemView;

@end

@implementation MyTabbar

-(WelfareBarItemView *)welfareBarItemView

{

if (!_welfareBarItemView) {

CGFloat tabBarButtonW = SCREEN_WIDTH / 5;

_welfareBarItemView = [[WelfareBarItemView alloc] initWithFrame:CGRectMake(tabBarButtonW * 2, -15, tabBarButtonW, 64)];

}

return _welfareBarItemView;

}

- (instancetype)init

{

self = [super init];

if (self) {

[self addSubview:self.welfareBarItemView];

self.barTintColor = [UIColor whiteColor];

UIButton * button = [[UIButton alloc] init];

button.backgroundColor = [UIColor clearColor];

[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];

[self addSubview:button];

[button zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {

layout.topSpace(0);

layout.leftSpace(0);

layout.rightSpace(0);

layout.bottomSpace(0);

}];

}

return self;

}

-(void)layoutSubviews

{

[super layoutSubviews];

// 设置其他tabbarButton的frame

CGFloat tabBarButtonW = SCREEN_WIDTH / 5;

CGFloat tabBarButtonIndex = 0;

for (UIView *child in self.subviews) {

Class class = NSClassFromString(@"UITabBarButton");

if ([child isKindOfClass:class]) {

// 设置x

CGRect rect = child.frame;

rect.origin.x = tabBarButtonIndex * tabBarButtonW;

// 设置宽度

rect.size.width = tabBarButtonW;

child.frame = rect;

// 增加索引

tabBarButtonIndex++;

if (tabBarButtonIndex == 2) {

tabBarButtonIndex++;

}

}

}

}

-(void) buttonClick

{

self.block();

}

@end


MyTabBarViewController中:

MyTabbar * tabBar = [[MyTabbar alloc] init];

__weak typeof(self)weakSelf = self;

tabBar.block = ^(){

[weakSelf presentMoneyViewController];

};

[self setValue:tabBar forKey:@"tabBar"];


MyTabBarViewController参考:https://github.com/Damonvvong/DWCustomTabBarDemo

你可能感兴趣的:(自定义tabbar)