1.刪除自己的TabBar
- (void)setUpTabBar
{
[self.tabBar removeFromSuperview];
HANTabBar *tabBar = [[HANTabBar alloc] init];
tabBar.frame = self.tabBar.frame;
tabBar.items = self.items;
tabBar.delegate = self;
[self.view addSubview:tabBar];
}
2.自定義TabBar繼承UIView并設(shè)置代理(通過代理傳遞選中了那個(gè)UITabBarItem)
#import
@class HANTabBar;
@protocol HANTabBarDelegate
@optional
- (void)tabBar:(HANTabBar *)tabBar index:(NSInteger)index;
@end
@interface HANTabBar : UIView
@property(nonatomic,strong)NSArray *items;
//代理
@property(nonatomic,weak)id delegate;
@end
3、添加自定義的TabBarItem(UIBUtton)添加到自定義的TabBar上
- (void)setItems:(NSArray *)items
{
_items = items;
int i = 0;
for (UITabBarItem *ite in items) {
HANTabButton *button = [[HANTabButton alloc] init];
[button setTitle:ite.title forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self addSubview:button];
i++;
}
}
4、布局添加的Button
- (void)layoutSubviews
{
CGFloat buttonW = self.frame.size.width / self.items.count;
CGFloat buttonH = self.frame.size.height;
int i = 0;
for (UIButton *button in self.subviews) {
button.frame = CGRectMake(i * buttonW, 0, buttonW, buttonH);
i++;
}
}
演示代碼下載地址:https://yunpan.cn/cqkWwhUVxqQYK(提取碼:0a3d)