需求
之前已經(jīng)實現(xiàn)了自定義TabBar,如圖所示:
自定義TabBar.jpeg
現(xiàn)在需要實現(xiàn)一個類似今日頭條TabBar的功能 —— 如果繼續(xù)點擊當前TabBar的選中項发绢,那么該界面需要刷新UITableView泛范。
分析
既然已經(jīng)自定義了TabBar,那么最簡單的就是在自定義中給TabBar中需要的UITabBarButton
添加事件 —— 點擊就發(fā)送通知掂榔,并且將當前的索引傳出去黑竞。對應的界面監(jiān)聽通知眨层,拿到索引比對匣距,如果和當前索引一致,就執(zhí)行對應的操作哎壳。
實現(xiàn)
- 自定義TabBar的layoutSubviews中綁定事件
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIButton * tabBarButton in self.subviews) {
if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
//監(jiān)聽tabbar的點擊
//綁定tag 標識
tabBarButton.tag = index;
//監(jiān)聽tabbar的點擊
[tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
}
- 監(jiān)聽事件毅待,發(fā)送通知
- (void)tabBarButtonClick:(UIControl *)tabBarBtn{
//判斷當前按鈕是否為上一個按鈕
//再次點擊同一個item時發(fā)送通知出去 對應的VC捕獲并判斷
if (self.previousClickedTag == tabBarBtn.tag) {
[[NSNotificationCenter defaultCenter] postNotificationName:
@"DoubleClickTabbarItemNotification" object:@(tabBarBtn.tag)];
}
self.previousClickedTag = tabBarBtn.tag;
}
- 對應的UIViewController監(jiān)聽通知
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doubleClickTab:) name:@"DoubleClickTabbarItemNotification" object:nil];
}
- 監(jiān)聽到通知,比對后執(zhí)行操作
-(void)doubleClickTab:(NSNotification *)notification{
//這里有個坑 就是直接用NSInteger接收會有問題 數(shù)字不對
//因為上個界面?zhèn)鬟^來的時候封裝成了對象归榕,所以用NSNumber接收后再取值
NSNumber *index = notification.object;
if ([index intValue] == 1) {
//刷新
}
}
2018.4.28 補充
本文被轉載后尸红,有很多好心的讀者進行批評指正:這種方式不夠優(yōu)雅,不夠簡單刹泄。怎么最簡單呢外里?其實只要重寫UITabBarController
的代理就可以實現(xiàn),方法如下
//這個是UITabBarController的代理方法
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
// 判斷哪個界面要需要再次點擊刷新特石,這里以第一個VC為例
if ([tabBarController.selectedViewController isEqual:[tabBarController.viewControllers firstObject]]) {
// 判斷再次選中的是否為當前的控制器
if ([viewController isEqual:tabBarController.selectedViewController]) {
// 執(zhí)行操作
NSLog(@"刷新界面");
return NO;
}
}
return YES;
}