一、控制器部分
#import "JRTabBarConroller.h"
#import "JRTabBar.h"
@interface JRTabBarConroller ()<JRTabBarProtocol>
@property(nonatomic,weak) UIViewController * currentVC;
@end
@implementation JRTabBarConroller
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor blackColor];
//1 添加当前显示的控制器
[self _setUpSelectController:0];
//2 添加tabbar
[self _setUpTabbar];
}
#pragma mark - 添加tabbar
- (void) _setUpTabbar{
JRTabBar * tab=[[JRTabBar alloc] initWithFrame:CGRectMake(0, kHeight-49,kWidth , 49) andItems:self.items];
tab.delegate=self;
[self.view addSubview:tab];
tab.hidden = self.tabbarHidden;
}
//设置视图控制器
- (void)_setUpSelectController:(NSInteger) index{
//如果重复点击,取消操作
UIViewController * vc=self.viewControllers[index];
if(self.currentVC==vc)return;
//第一次不进行动画
if(self.currentVC==nil){
[self.view addSubview:vc.view];
self.currentVC=vc;
}else{
//第二次开始加载动画
//将当前的视图快速移动到屏幕的最边缘位置,然后在动画慢慢的拉回来从而达到翻页效果
[self.view insertSubview:vc.view aboveSubview:self.currentVC.view];
vc.view.transform=CGAffineTransformMakeTranslation(kWidth, 0);
[UIView animateWithDuration:0.5 animations:^{
vc.view.transform=CGAffineTransformIdentity;
} completion:^(BOOL finished) {
[self.currentVC.view removeFromSuperview];//移除控制器的view,防止重复添加
self.currentVC=vc;
}];
}
}
#pragma mark - JRTabBarProtocol
- (void)changeVC:(NSInteger)index{
NSInteger tag=index-100;
// 重新切换控制器
[self _setUpSelectController:tag];
}
@end
二、模型部分定义的属性和方法
@property(nonatomic,copy) NSString * title;
/** 图片*/
@property(nonatomic,strong) UIImage * image;//注意uimage使用的是strong,uiimage不是视图
/** 选中时图片*/
@property(nonatomic,strong) UIImage * imageSelected;
- (instancetype)initWithTitle:(NSString *) title andImage:(UIImage *) image;
三、自定义的tabBar部分
@implementation JRTabBar
-(instancetype)initWithFrame:(CGRect)frame andItems:(NSArray *) array{
self = [super initWithFrame:frame];
if (self) {
self.itemArray=array;
[self addItems];
//默认灰色
self.backgroundColor=[UIColor lightGrayColor];
}
return self;
}
#pragma mark - 增加item
- (void)addItems{
CGFloat space =(kWidth-2*kEdgeMargin-self.itemArray.count*40)/(self.itemArray.count-1);
for (int i=0;i<self.itemArray.count;i++) {
JRItem *item= [[[NSBundle mainBundle] loadNibNamed:@"jritem" owner:nil options:nil] firstObject];
item.tag=100+i;
//1 初始化item
JRItemModel * model=self.itemArray[i];
item.imageView.image=model.image;
item.label.text=model.title;
//2 修改坐标
CGRect frame=item.frame;
frame.origin.x=kEdgeMargin+i*(space+40);
item.frame=frame;
//3加入tabbar
[self addSubview:item];
//增加点击手势
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showInfo:)];
[item addGestureRecognizer:tap];
}
}
- (void) showInfo:(UITapGestureRecognizer *) ges{
NSInteger tag= ges.view.tag;
[self.delegate changeVC:tag];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。