iOS拦截控件事件,处理后继续执行原来的消息传递流程

本文介绍了如何在iOS中拦截UIEvent事件,并在处理后继续执行原有的消息传递流程。通过Objective-C runtime方法交换,实现对UIWindow的sendEvent:方法的拦截,从而在事件触发时进行自定义操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#import <objc/objc.h>

#import <objc/runtime.h>



- (void)sendEventHooked:(UIEvent *)event {

    

    

    //在这里做你想做的事情吧

   NSLog(@"截获事件:%@", [eventdescription]);

    

    

    

    //执行原来的消息传递流程

    

    [selfperformSelector:@selector(sendEventOriginal:)withObject:event];

    

}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{


    Method sendEvent =class_getInstanceMethod([UIWindowclass],@selector(sendEvent:));

   Method sendEventMySelf =class_getInstanceMethod([selfclass], @selector(sendEventHooked:));

   IMP sendEventImp =method_getImplementation(sendEvent);

   class_addMethod([UIWindowclass],@selector(sendEventOriginal:), sendEventImp,method_getTypeEncoding(sendEvent));

   IMP sendEventMySelfImp =method_getImplementation(sendEventMySelf);

   class_replaceMethod([UIWindowclass],@selector(sendEvent:), sendEventMySelfImp,method_getTypeEncoding(sendEvent));


    

self.window = [[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]]autorelease];

    // Override point for customization after application launch.

    if ([[UIDevicecurrentDevice]userInterfaceIdiom] ==UIUserInterfaceIdiomPhone) {

        self.viewController = [[[ViewControlleralloc]initWithNibName:@"ViewController_iPhone"bundle:nil]autorelease];

    }else {

        self.viewController = [[[ViewControlleralloc]initWithNibName:@"ViewController_iPad"bundle:nil]autorelease];

    }

    self.window.rootViewController =self.viewController;

    [self.windowmakeKeyAndVisible];


return YES;

}




然后可以在其它地方创建按钮,就可以截获到按钮触摸事件!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值