以监听UITabBarButton的点击事件为例:
1.tabBar是自定义的,那么遍历其中子控件,找到按钮直接监听
- (void)layoutSubviews
{
[super layoutSubviews];
//调整内部子控件的位置
CGFloat btnX = 0;
CGFloat btnY = 0;
CGFloat btnW = self.width / count;
CGFloat btnH = self.height;
int i = 0;
//遍历子控件
for (UIControl *tabBarButton in self.subviews) {
if (![tabBarButtonisKindOfClass:NSClassFromString(@"UITabBarButton")])continue;
if(i == 0 && self.previousClickedTabBarButton== nil) { //最前面的tabBarButton
self.previousClickedTabBarButton = tabBarButton;
}
// 监听点击
[tabBarButton addTarget:self action:@selector(tabBarButtonClick:)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)tabBarButtonClick:(UIControl
*)tabBarButton
{
if(self.previousClickedTabBarButton== tabBarButton) {
// 告诉外界,tabBarButton被重复点击了
[[NSNotificationCenterdefaultCenter] postNotificationName:MYTabBarButtonDidRepeatClickNotification object:nil];
}
self.previousClickedTabBarButton= tabBarButton;
}
2.可以尝试成为其父控件tabBar的代理,并实现代理方法监听
(在UITabBarController中不适用,因为控制器已经是tabBar的代理,更改时会报错)
#pragma mark - tabbar的代理方法
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{// 这里不需要调用super,因为父类没有实现这个代理方法
}
/*
Changing the delegate of 【a tab bar managed by a tab bar controller】 is not allowed.
被UITabBarController所管理的UITabBar,它的delegate不允许被修改
*/
3.方法2不适用的情况下,可以尝试在创建时成为UITabBarController控制器的代理(需要强制转换,遵守其代理协议)
//在AppDelegate中直接创建,需遵守协议
#import "AppDelegate.h"
#import "MYTabBarController.h"
#import "MYADViewController.h"
@interface AppDelegate () <UITabBarControllerDelegate>
@property (nonatomic, strong) UIWindow *topWindow;
@end
@implementation AppDelegate
#pragma mark - <UIApplicationDelegate>
// 程序启动的时候调用
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions {
//1.创建窗口
self.window= [[UIWindowalloc] initWithFrame:[UIScreenmainScreen].bounds];
//创建并成为代理
MYTabBarController *tabBarVc = [[MYTabBarController alloc] init];
tabBarVc.delegate = self;//成为代理
self.window.rootViewController = tabBarVc;
//3.显示窗口makeKey:UIApplication主窗口
//窗口会把根控制器的view添加到窗口
[self.window makeKeyAndVisible];
returnYES;
}
#pragma mark - <UITabBarControllerDelegate>
//利用其代理方法就实现功能
- (void)tabBarController:(UITabBarController
*)tabBarController didSelectViewController:(UIViewController
*)viewController;