首先,新建一个自定义的tabbar 继承UITabBar
#import "ZGTabBar.h"
@interface ZGTabBar()
@property (nonatomic, weak) UIButton *plusBtn;
@end
@implementation ZGTabBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 添加一个按钮到tabbar中
UIButton *plusBtn = [[UIButton alloc] init];
//.....一系列对button的设置
plusBtn.size = plusBtn.currentBackgroundImage.size;
[plusBtn addTarget:self action:@selector(plusClick) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:plusBtn];
self.plusBtn = plusBtn;
}
return self;
}
/**
* 加号按钮点击
*/
- (void)plusClick
{
// 通知代理
if ([self.delegate respondsToSelector:@selector(tabBarDidClickPlusButton:)]) {
[self.delegate tabBarDidClickPlusButton:self];
}
}
- (void)layoutSubviews
{
#warning [super layoutSubviews] 一定要调用
[super layoutSubviews];
// 1.设置加号按钮的位置
self.plusBtn.centerX = self.width * 0.5;
self.plusBtn.centerY = self.height * 0.5;
// 2.设置其他tabbarButton的位置和尺寸
CGFloat tabbarButtonW = self.width / 5;
CGFloat tabbarButtonIndex = 0;
for (UIView *child in self.subviews) {
Class class = NSClassFromString(@"UITabBarButton");
if ([child isKindOfClass:class]) {
// 设置宽度
child.width = tabbarButtonW;
// 设置x
child.x = tabbarButtonIndex * tabbarButtonW;
// 增加索引
tabbarButtonIndex++;
if (tabbarButtonIndex == 2) {
tabbarButtonIndex++;
}
}
}
}
@end
然后再在tabBarController中替换系统自带的tabbar
#import "ZGTabBarViewController.h"
#import "ZGTabBar.h"
@implementation HWTabBarViewController
- (void)viewDidLoad
{
[super viewDidLoad];
ZGTabBar *tabBar = [[HWTabBar alloc] init];
[self setValue:tabBar forKeyPath:@"tabBar"];
/*
[self setValue:tabBar forKeyPath:@"tabBar"];相当于self.tabBar = tabBar;
[self setValue:tabBar forKeyPath:@"tabBar"];这行代码过后,tabBar的delegate就是HWTabBarViewController
说明,不用再设置tabBar.delegate = self;
*/
/*
1.如果tabBar设置完delegate后,再执行下面代码修改delegate,就会报错
tabBar.delegate = self;
2.如果再次修改tabBar的delegate属性,就会报下面的错误
错误信息:Changing the delegate of a tab bar managed by a tab bar controller is not allowed.
错误意思:不允许修改TabBar的delegate属性(这个TabBar是被TabBarViewController所管理的)
*/
}
@end