需求
之前已經實現了自定義TabBar,如圖所示:
自定義TabBar.jpeg
現在需要實現一個類似今日頭條TabBar的功能 ―― 如果繼續點擊當前TabBar的選中項,那么該界面需要刷新UITableView。
分析
既然已經自定義了TabBar,那么最簡單的就是在自定義中給TabBar中需要的UITabBarButton添加事件 ―― 點擊就發送通知,并且將當前的索引傳出去。對應的界面監聽通知,拿到索引比對,如果和當前索引一致,就執行對應的操作。
實現
1. 自定義TabBar的layoutSubviews中綁定事件
- (void)layoutSubviews{ [super layoutSubviews]; for (UIButton * tabBarButton in self.subviews) { if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) { //監聽tabbar的點擊 //綁定tag 標識 tabBarButton.tag = index; //監聽tabbar的點擊 [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside]; } }}
2. 監聽事件,發送通知
- (void)tabBarButtonClick:(UIControl *)tabBarBtn{ //判斷當前按鈕是否為上一個按鈕 //再次點擊同一個item時發送通知出去 對應的VC捕獲并判斷 if (self.previousClickedTag == tabBarBtn.tag) { [[NSNotificationCenter defaultCenter] postNotificationName: @"DoubleClickTabbarItemNotification" object:@(tabBarBtn.tag)]; } self.previousClickedTag = tabBarBtn.tag;}
對應的UIViewController監聽通知
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doubleClickTab:) name:@"DoubleClickTabbarItemNotification" object:nil];}
3. 監聽到通知,比對后執行操作
-(void)doubleClickTab:(NSNotification *)notification{ //這里有個坑 就是直接用NSInteger接收會有問題 數字不對 //因為上個界面傳過來的時候封裝成了對象,所以用NSNumber接收后再取值 NSNumber *index = notification.object; if ([index intValue] == 1) { //刷新 }}
最終的效果請看:
總結
以上所述是小編給大家介紹的iOS開發中TabBar再次點擊實現刷新效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答