- (void)addItemWithIcon:(NSString *)icon title:(NSString *)title {
//1.初始化
CustomTabBarItem *item = [[CustomTabBarItem alloc]init];
[item setImage:[UIImage imageNamed:icon] forState:UIControlStateNormal];
[item setTitle:title forState:UIControlStateNormal];
[item addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
//2.添加子视图
[self addSubview:item];
//3.调整item的frame
[self itemFrame];
}
//很好地一个方法
- (void)itemFrame {
NSInteger count = self.subviews.count;
CGFloat height = CGRectGetHeight(self.bounds);
CGFloat width = CGRectGetWidth(self.bounds) / count;
for (int i = 0; i < count; i ++) {
CustomTabBarItem *tabBarItem = self.subviews[i];
tabBarItem.tag = i; //绑定标记
tabBarItem.frame = CGRectMake(width * i, 0, width, height);
}
}
自定义标签View (
CustomTabBarItem (按钮)
)
可重用性高,
设置点击事件监听的代理
@protocol CustomTabBarDlegate <NSObject>
@optional
- (void)customTabBar:(CustomTabBarView *)tabBar itemSelectedFrom:(NSInteger)from to:(NSInteger)to;
@end
@property (nonatomic,weak)id<CustomTabBarDlegate> delegate;
- (void)buttonPressed:(CustomTabBarItem *)item {
//通知代理:
if ([_delegate respondsToSelector:@selector(customTabBar:itemSelectedFrom:to:)]) {
[_delegate customTabBar:self itemSelectedFrom:_selectedItem.tag to:item.tag];
}
_selectedItem = item;
}
在外面使用:(要增加标签直接再写add方法就行了)
//1.添加 CustomTabBarView
customTabBarView = [[CustomTabBarView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - CUSTOMTABBARVIEW_HEIGHT,CGRectGetWidth(self.view.bounds), CUSTOMTABBARVIEW_HEIGHT)];
customTabBarView.delegate = self;
[self.view addSubview:customTabBarView];
//2.往 CustomTabBarView 里添加内容
[customTabBarView addItemWithIcon:@"商品" title:@"xiangu"];
[customTabBarView addItemWithIcon:@"消息" title:@"xiangu"];
[customTabBarView addItemWithIcon:@"订单" title:@"xiangu"];
//3.添加其他控制器
[self customTabBar:customTabBarView itemSelectedFrom:0 to:0];
#pragma mark - CustomTabBarView的代理方法
- (void)customTabBar:(CustomTabBarView *)tabBar itemSelectedFrom:(NSInteger)from to:(NSInteger)to {
NSLog(@"%ld,%ld",from,to);
[_currentVC.view removeFromSuperview];
[_currentVC removeFromParentViewController];
if (to == 0) {
UIViewController *vc = [[UIViewController alloc]init];
self.view.backgroundColor = [UIColor greenColor];
[self.view addSubview:vc.view];
[self addChildViewController:vc];
_currentVC = vc;
}else if (to == 1){
UIViewController *vc = [[UIViewController alloc]init];
vc.view.backgroundColor = [UIColor redColor];
[self.view addSubview:vc.view];
[self addChildViewController:vc];
_currentVC = vc;
}else {
UIViewController *vc = [[UIViewController alloc]init];
vc.view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:vc.view];
[self addChildViewController:vc];
_currentVC = vc;
}
[self.view bringSubviewToFront:customTabBarView];
}