
[图二.png]
2、由于UITabBar是readonly的,所以我们不能直接对他进行赋值,这里利用KVC访问私有变量将MCTabBar赋值给"tabBar"
**具体实现**
MCTabBar
```
#import
@interface MCTabBar : UITabBar
@property (nonatomic, strong) UIButton *centerBtn; //中间按钮
@end
```
```
@implementation MCTabBar
- (instancetype)init{
if (self = [super init]){
[self initView];
}
return self;
}
- (void)initView{
_centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
// 设定button大小为适应图片
UIImage *normalImage = [UIImage imageNamed:@"tabbar_add"];
_centerBtn.frame = CGRectMake(0, 0, normalImage.size.width, normalImage.size.height);
[_centerBtn setImage:normalImage forState:UIControlStateNormal];
//去除选择时高亮
_centerBtn.adjustsImageWhenHighlighted = NO;
//根据图片调整button的位置(图片中心在tabbar的中间最上部,这个时候由于按钮是有一部分超出tabbar的,所以点击无效,要进行处理)
_centerBtn.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - normalImage.size.width)/2.0, - normalImage.size.height/2.0, normalImage.size.width, normalImage.size.height);
[self addSubview:_centerBtn];
}
//处理超出区域点击无效的问题
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView *view = [super hitTest:point withEvent:event];
if (view == nil){
//转换坐标
CGPoint tempPoint = [self.centerBtn convertPoint:point fromView:self];
//判断点击的点是否在按钮区域内
if (CGRectContainsPoint(self.centerBtn.bounds, tempPoint)){
//返回按钮
return _centerBtn;
}
}
return view;
}
```
利用KVC赋值
```
//MCTabBarController.m
- (void)viewDidLoad {
[super viewDidLoad];
_mcTabbar = [[MCTabBar alloc] init];
[_mcTabbar.centerBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//选中时的颜色
_mcTabbar.tintColor = [UIColor colorWithRed:27.0/255.0 green:118.0/255.0 blue:208/255.0 alpha:1];
//透明设置为NO,显示白色,view的高度到tabbar顶部截止,YES的话到底部
_mcTabbar.translucent = NO;
//利用KVC 将自己的tabbar赋给系统tabBar
[self setValue:_mcTabbar forKeyPath:@"tabBar"];
self.delegate = self;
[self addChildViewControllers];
}
```
* 点击旋转
在中间按钮的点击事件执行时旋转第二个index,然后执行旋转动画,
在tabbar的代理事件中监听旋中中间按钮的事件,然后执行旋转动画,其他按钮则移除动画,代码如下
```
- (void)buttonAction:(UIButton *)button{
self.selectedIndex = 2;//关联中间按钮
[self rotationAnimation];
}
//tabbar选择时的代理
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
if (tabBarController.selectedIndex == 2){//选中中间的按钮
[self rotationAnimation];
}else {
[_mcTabbar.centerBtn.layer removeAllAnimations];
}
}
//旋转动画
- (void)rotationAnimation{
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
rotationAnimation.duration = 3.0;
rotationAnimation.repeatCount = HUGE;
[_mcTabbar.centerBtn.layer addAnimation:rotationAnimation forKey:@"key"];
}










