1.创建一个View继承自UIView,做为TabBar,WWTabBarView.m
<span style="font-size:14px;">@implementation WWTabBarView</span>
2.提供类方法进行创建,传入系统自带的TabBar,就可以替换系统的tabBar
+ (instancetype)tabBarWithSystemTabBar:(UITabBar *)sTabBar
{
WWTabBarView *tabBar = [[WWTabBarView alloc] init];
tabBar.frame = sTabBar.bounds;
[sTabBar addSubview:tabBar];
return tabBar;
}
3. 在控制器中根据NavigationController的信息添加TabBar上的按钮,并绑定按钮的tag,作为页面跳转的标识
//
传入一个
tabBarItem
设置
tabBar
的按钮的图片
- (void)addTabBarItemWithItem:(UITabBarItem *)item
{
NSUInteger count = self.subviews.count;
WWTabBarButton *tabBarButton = [WWTabBarButton buttonWithType:UIButtonTypeCustom];
tabBarButton.tag = count;
[btn setImage:item.image forState:UIControlStateNormal];
[btn setImage:item.selectedImage forState:UIControlStateSelected];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
if (count == 0) {
[self btnClick:btn];
}
[self addSubview:tabBarButton];
}
4. 设置选中改变状态
- (void)btnClick:(WWTabBarBotton *)btn
{
_selButton.selected = NO;
btn.selected = YES;
_selButton = btn;
if ([self.delegate respondsToSelector:@selector(WWTabBarClick:selIndex:)]) {
[self.delegate WWTabBarClick:self selIndex:btn.tag];
}
}
5. 根据按钮的位置进行布局
- (void)layoutSubviews
{
NSUInteger count = self.subviews.count;
for (int i = 0; i < count; i ++) {
WWTabBarBotton *btn = self.subviews[i];
CGFloat btnW = self.bounds.size.width / count;
CGFloat btnX = btnW *i;
CGFloat btnH = self.bounds.size.height ;
[btn setFrame:CGRectMake(btnX, 0, btnW, btnH)];
}
}
6. 创建代理用于传递当前选中按钮的序号
- (void)WWTabBarClick:(WWTabBarView *)tabBarView selIndex:(NSUInteger)index
使用方法:
1. 在控制器中自定义TabBar
<span style="color: rgb(187, 44, 162); font-family: Menlo; font-size: 13px;">@property</span><span style="font-family: Menlo; font-size: 13px;"> (</span><span style="color: rgb(187, 44, 162); font-family: Menlo; font-size: 13px;">nonatomic</span><span style="font-family: Menlo; font-size: 13px;">, </span><span style="color: rgb(187, 44, 162); font-family: Menlo; font-size: 13px;">strong</span><span style="font-family: Menlo; font-size: 13px;">) </span><span style="font-family: Menlo; font-size: 13px; color: rgb(79, 129, 135);">WWTabBarView</span><span style="font-family: Menlo; font-size: 13px;"> *customTabBar;</span>
_customTabBar = [WWTabBarView tabBarWithSystemTabBar:self.tabBar];
2. 在自定义TabBar中添加完子控件后删除系统自带的TabBar
<span style="font-size:14px;">- (void)removeChildButton
{
for (UIView *tabBarItem in self.subviews) {
if (! [tabBarItem isKindOfClass:[WWTabBarView class]]) {
[tabBarItem removeFromSuperview];
}
}
}</span>