监听某个对象事件的几种方法

以监听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;

复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值