// 1、创建一个LZTabBar
LZTabBar *myTabBar = [[LZTabBar alloc]init];
myTabBar.frame = self.tabBar.bounds;
myTabBar.delegate = self;
[self.tabBar addSubview:myTabBar];
// 2、添加按钮到tabBar
NSString *selName = @"selImageName";
NSString *norName = @"norImageName";
[myTabBar addButtonWithNorName:norName selName:selName];
// 3、代理 -- 切换控制器
- (void)tabBar:(LZTabBar *)tabBar didSelectButtonFrom:(int)from to:(int)to {
self.selectedIndex = to;
}
// LZTabBar.h
#import <UIKit/UIKit.h>
@class LZTabBar;
/**
* 定义协议
*/
@protocol LZTabBarDelegate <NSObject>
/**
* 选中某个button
*
* @param tabBar LZTabBar
* @param from index button from
* @param to index button to tag
*/
- (void)tabBar:(LZTabBar *)tabBar didSelectButtonFrom:(int)from to:(int)to;
@optional
@end
@interface LZTabBar : UIView
/**
* 向LZTabBar添加按钮
*/
- (void)addButtonWithNorName:(NSString *)norName selName:(NSString *)selName;
/**
* LZTabBar 代理对象
*/
@property (nonatomic, weak) id <LZTabBarDelegate> delegate;
@end
// LZTabBar.m
#import "LZTabBar.h"
#import "LZTabBarButton.h"
@interface LZTabBar ()
/**
* 记录被选中的button
*/
@property (nonatomic, weak) LZTabBarButton *selectedBtn;
@end
// 添加一个button到TabBar
- (void)addButtonWithNorName:(NSString *)norName selName:(NSString *)selName {
// 1、创建一个button,并设置他的背景图片 选中状态 和 正常状态
LZTabBarButton *btn = [LZTabBarButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:
[UIImage imageNamed:norName ] forState:UIControlStateNormal];
[btn setBackgroundImage:
[UIImage imageNamed:selName ] forState:UIControlStateSelected];
// 2、为button绑定 监听方法,监听按下事件
[btn addTarget:self action:@selector(buttonSelcected:)
forControlEvents:UIControlEventTouchDown];
// 3、把这个button 添加到view里面去
[self addSubview:btn];
// 4、默认选中第一个控制器
if (self.subviews.count == 1) {
[self buttonSelcected:btn];
}
}
// 按钮按下事件处理
- (void)buttonSelcected: (LZTabBarButton *)btn {
// 1、通知代理,选中事件
if ([self.delegate respondsToSelector:
@selector(tabBar:didSelectButtonFrom:to:)]) {
[self.delegate tabBar:self
didSelectButtonFrom: (int)self.selectedBtn.tag to: (int)btn.tag];
}
// 2、取消选中记录选中按钮的selected属性
self.selectedBtn.selected = NO;
// 3、设置当前按下按钮为选中状态
btn.selected = YES;
// 4、更新选中按钮
self.selectedBtn = btn;
}
// 重新布局时设置按钮的frame
- (void)layoutSubviews {
[super layoutSubviews];
/** 计算btn的frame*/
int count = (int)self.subviews.count;
for (int i = 0; i < count; i++) {
LZTabBarButton *btn = self.subviews[i];
btn.tag = i;
CGFloat btnY = 0;
CGFloat btnW = self.frame.size.width / count;
CGFloat btnH = self.frame.size.height;
CGFloat btnX = i * btnW;
btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
}