以監聽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;
複製程式碼