如何监听Tabbar的点击
如果不是自定义的Tabbar
- 实现
UITabBarController
的代理方法tabBarController: didSelectViewController:
, 每次Tabbar被点击了都会来到这个代理方法 - 在这个代理方法中发送通知
- 在需要监听Tabbar点击的控制器中监听上面发出的通知
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
[[NSNotificationCenter defaultCenter] postNotificationName:AHTabBarDidSelectNotification object:nil userInfo:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarSelect) name:AHTabBarDidSelectNotification object:nil];
- (void)tabBarSelect{
// 如果是连续选中2次, 直接刷新
if(self.lastSelectedIndex == self.tabBarController.selectedIndex && self.view.isShowingOnKeyWindow){
[self.tableView.mj_header beginRefreshing]
}
self.lastSelectedIndex = self.tabBarController.selectedIndex
}
如果是自定义的Tabbar
- 在自定义的Tabbar中, 给Tabbar中的
UITabBarButton
添加Target
, 每次UITabBarButton
一点击, 就发送通知, 剩下的基本和上面一样
自定义的tabbar
#import <UIKit/UIKit.h>
@interface AHTabBar : UITabBar
@end
#import "AHTabBar.h"
#import "AHPublishView.h"
@interface AHTabBar()
@property (strong, nonatomic) UIButton *publishButton;
@end
@implementation AHTabBar
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self){
[self setBackgroundImage:[UIImage imageNamed:@"tabbar-light"]];
UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
[publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
[publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon_click"] forState:UIControlStateHighlighted];
publishButton.size = publishButton.currentBackgroundImage.size;
[publishButton addTarget:self action:@selector(publishClick) forControlEvents:UIControlEventTouchUpInside];
self.publishButton = publishButton;
[self addSubview:publishButton];
}
return self;
}
- (void)layoutSubviews{
[super layoutSubviews];
static BOOL added = NO;
CGFloat width = self.width;
CGFloat height = self.height;
self.publishButton.center = CGPointMake(width * 0.5, height * 0.5);
CGFloat buttonY = 0;
CGFloat buttonW = width / 5;
CGFloat buttonH = height;
NSInteger index = 0;
for(UIControl *button in self.subviews){
if (![button isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;
CGFloat buttonX = buttonW * ((index > 1)?(index + 1):index);
button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
index++;
if(added == NO){
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
}
}
added = YES;
}
- (void)buttonClick{
[[NSNotificationCenter defaultCenter] postNotificationName:AHTabBarDidSelectNotification object:nil userInfo:nil];
}
- (void)publishClick{
[AHPublishView show];
}
@end