系統預設的 UITabBar 樣式有限,當我們需要更個性化的底部導航欄時,就需要自定義 TabBar。本文示範如何透過「自定義一個 view 並覆蓋原生 tabBar」的思路,實現一個完全可控的自定義底部導航欄。
核心思路只有兩步:
這樣既保留了 UITabBarController 的頁面切換能力,又能自由掌控底部導航欄的樣式與交互。
先在 Storyboard 中拉一個 Tab Bar Controller,然後用 Command + N 分別建立兩個文件:一個繼承自 UITabBarController(如 PLTabBarController),一個繼承自 UIView(如 TabBarView)。
#import "PLTabBarController.h"
#import "TabBarView.h"
@interface PLTabBarController () <TabBarViewDelegate> @end
@implementation PLTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
TabBarView *tabbar = [[TabBarView alloc] init];
tabbar.frame = self.tabBar.bounds;
tabbar.delegate = self;
NSString *imageName = nil;
NSString *selName = nil;
for (int i = 0; i < self.childViewControllers.count; i++) {
imageName = [NSString stringWithFormat:@"%d", i + 1];
selName = [NSString stringWithFormat:@"s%d", i + 1];
[tabbar addTarBarButtonWithName:imageName selName:selName];
}
// 把自定義 view 覆蓋到原生 tabBar 上
[self.tabBar addSubview:tabbar];
}
// 通過代理切換子控制器
- (void)tabbar:(TabBarView *)tabbar didSelectedIndex:(NSInteger)selectIndex {
self.selectedIndex = selectIndex;
}
@end
#import <UIKit/UIKit.h> @class TabBarView; @protocol TabBarViewDelegate <NSObject> @optional - (void)tabbar:(TabBarView *)tabbar didSelectedIndex:(NSInteger)selectIndex; @end @interface TabBarView : UIView @property (nonatomic, weak) id <TabBarViewDelegate> delegate; - (void)addTarBarButtonWithName:(NSString *)name selName:(NSString *)selName; @end
#import "TabBarView.h"
@interface TabBarView ()
@property (nonatomic, weak) UIButton *selectedBtn;
@end
@implementation TabBarView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) { }
return self;
}
- (void)addTarBarButtonWithName:(NSString *)name selName:(NSString *)selName {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:selName] forState:UIControlStateSelected];
[button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
- (void)btnClicked:(UIButton *)button {
self.selectedBtn.selected = NO;
button.selected = YES;
self.selectedBtn = button;
if ([self.delegate respondsToSelector:@selector(tabbar:didSelectedIndex:)]) {
[self.delegate tabbar:self didSelectedIndex:button.tag];
}
}
// 均勻布局所有按鈕
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat btnX = 0;
CGFloat btnY = 0;
CGFloat btnW = self.frame.size.width / self.subviews.count;
CGFloat btnH = self.frame.size.height;
for (int i = 0; i < self.subviews.count; i++) {
UIButton *btn = self.subviews[i];
btn.tag = i;
btnX = i * btnW;
[btn setFrame:CGRectMake(btnX, btnY, btnW, btnH)];
if (i == 0) {
[self btnClicked:btn]; // 默認選中第一個
}
}
}
@end
透過這套「自定義 view + 覆蓋」的方案,我們就能打造出一個外觀、交互完全自主掌控的底部導航欄,滿足各種個性化的設計需求。