UITabBarController的使用过程中,可能会出现需要自定义UITabBar样式的时候,下面介绍两种实现方法。
方法1
存在N个视图控制器,且需要使用自定义的UITabBar样式来进行交互操作哪个视图控制器的显示。具体做法是在UITabBarController中的view中添加自定义样式的子视图,设置子视图响应方法跳转对应的视图控制器,然后再通过UITabBarController的代理方法重置自定义样式的子视图状态。
代码示例,继承UITabBarController的方式实现
#import "BaseTabBarController.h"
#import "MainVC.h"
#import "MineVC.h"
#import "AddVC.h"
@interface BaseTabBarController () <UITabBarControllerDelegate>
@property (nonatomic, strong) UIButton *addButton;
@end
@implementation BaseTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self initlizeAddButton];
}
#pragma mark - 实现
- (void)initlizeAddButton
{
self.delegate = self;
[self addChildVc:[[MainVC alloc] init] title:@"首页" image:@"homeNormal" selectedImage:@"homeSelected"];
[self addChildVc:[[AddVC alloc] init] title:nil image:nil selectedImage:nil];
[self addChildVc:[[MineVC alloc] init] title:@"我的" image:@"mineNormal" selectedImage:@"mineSelected"];
self.tabBar.backgroundColor = [UIColor yellowColor];
self.addButton = [[UIButton alloc] initWithFrame:CGRectMake((self.tabBar.frame.size.width - 70.0) / 2, (self.view.frame.size.height - 70.0) - 44.0, 70.0, 70.0)];
self.addButton.backgroundColor = [UIColor yellowColor];
self.addButton.layer.cornerRadius = 35;
self.addButton.layer.masksToBounds = YES;
[self.addButton setImage:[UIImage imageNamed:@"addNormal"] forState:UIControlStateNormal];
[self.addButton setImage:[UIImage imageNamed:@"addSelected"] forState:UIControlStateSelected];
[self.addButton addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.addButton];
[self.view bringSubviewToFront:self.addButton];
}
- (void)addClick:(UIButton *)button
{
button.selected = YES;
button.userInteractionEnabled = NO;
self.selectedIndex = 1;
}
- (void)addChildVc:(UIViewController *)childVc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
// 设置子控制器的文字(可以设置tabBar和navigationBar的文字)
if (title) {
childVc.title = title;
}
// 设置子控制器的tabBa