实现重写TabBar的TabBarItem,然后在中间额外加一个按钮。
.h文件
#import2
@interface WPTabBar : UITabBar
@end
.m文件
#import "WPTabBar.h"
@interface WPTabBar ()
//@property (nonatomic,weak)UIButton *centerButton;
@end
@implementation WPTabBar
- (void)layoutSubviews
{
[super layoutSubviews];
UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
[centerButton setImage:[UIImage imageNamed:@"tab_bar_ride0"] forState:UIControlStateNormal];
[centerButton setImage:[UIImage imageNamed:@"tab_bar_ride1"] forState:UIControlStateHighlighted];
// 一定要记得设置尺寸
[centerButton sizeToFit];
[self addSubview:centerButton];
// 获取子按钮总数
NSInteger count = self.items.count;
CGFloat x = 0;
CGFloat y = 0;
CGFloat w = self.width / (count + 1);
CGFloat h = self.height;
int i = 0;
// 遍历所有的tabBarButton
for (UIControl *tabBarButton in self.subviews) {
if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
if (i == 2) {
i += 1;
}
x = i * w;
// 设置UITabBarButton位置
tabBarButton.frame = CGRectMake(x, y, w, h);
tabBarButton.tag = i;
i++;
// 监听 UIControlEventTouchDownRepeat : 短时间内连续地重复点击
// [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDownRepeat];
[tabBarButton addTarget:self action:@selector(centerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
}
// 设置加号按钮位置
centerButton.center = CGPointMake(UIScreenWidth * 0.5, h * 0.5);
}
- (void)centerButtonClicked:(UIButton*)sender{
//可以在这里实现想要的操作,或者添加委托方法,让代理去实现
}
@end
在工程的tabbarController的viewDidLoad方法中实现自定义tabbar替换系统的tabbar,并且实现自定义tabbar的代理方法:
WPTabBar *tabBar = [[WPTabBar alloc] init];
// 设置代理
tabBar.delegate = self;
// KVC:如果要修系统的某些属性,但被设为readOnly,就是用KVC,即setValue:forKey:。
// 修改tabBar为自定义tabBar
[self setValue:tabBar forKey:@"tabBar"];