您的位置:首页 > 移动开发 > IOS开发

iOS事件拦截处理

2014-07-07 17:27 513 查看
前面分析了一通iOS事件的分发,主要介绍了事件如何找到处理的view,又是如何按照responder chain逐级传递的。这篇文章主要介绍iOS事件的拦截以及特殊处理。

        我们知道事件的分发是由Application到Window再到各级View的,所以显然最安全可靠的拦截地方是Application。这里拦截事件后如果不手动往下分发,则进入hit-test View过程的机会都没有。

        UIApplication和UIWindow都有sendEvent:方法,用来分发Event。我们可以继承类,重新实现sendEvent:方法,这样就可以拦截下事件,完成一些特殊的处理。

        比如:有一个iPad应用,要求在非某个特定view的区域触摸时进行一项处理。

        我们当然可以在其余每一个view里面增加代码进行判断,不过这样比较累,容易漏掉一些地方;另外当UI需求变更时,维护的GG往往会栽进这个坑,显然这不是一个好方法。

        这里比较简单的解决方案就是在继承UIApplication类,实现自己的sendEvent:,在这个方法里面初步过滤一下事件,是触摸事件就发送Notification,而特定的view会注册这个Notification,收到后判断一下是否触摸到了自己之外的区域。

        恩,还是上代码吧,比较清楚一点:

1. 继承UIApplication的DPApplication类

[objc] view
plaincopy





#import <UIKit/UIKit.h>  

  

extern NSString *const notiScreenTouch;  

  

@interface DPApplication : UIApplication  

  

@end  

[objc] view
plaincopy





#import "DPApplication.h"  

  

NSString *const notiScreenTouch = @"notiScreenTouch";  

  

@implementation DPApplication  

  

- (void)sendEvent:(UIEvent *)event  

{  

    if (event.type == UIEventTypeTouches) {  

        if ([[event.allTouches anyObject] phase] == UITouchPhaseBegan) {  

            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:notiScreenTouch object:nil userInfo:[NSDictionary dictionaryWithObject:event forKey:@"data"]]];  

        }  

    }  

    [super sendEvent:event];  

}  

  

@end  

2.要在main.m文件中替换掉UIApplication的调用

[objc] view
plaincopy





#import <UIKit/UIKit.h>  

  

#import "AppDelegate.h"  

#import "DPApplication.h"  

  

int main(int argc, charchar *argv[])  

{  

    @autoreleasepool {  

        //return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));  

        return UIApplicationMain(argc, argv, NSStringFromClass([DPApplication class]), NSStringFromClass([AppDelegate class]));  

    }  

}  

3. 这时已经实现了拦截消息,并在touchBegan的时候发送Notification,下面就是在view里面注册这个Notification并处理

[objc] view
plaincopy





[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onScreenTouch:) name:notiScreenTouch object:nil];  

[objc] view
plaincopy





- (void)onScreenTouch:(NSNotification *)notification  

{  

    UIEvent *event=[notification.userInfo objectForKey:@"data"];  

      

    NSLog(@"touch screen!!!!!");  

    CGPoint pt = [[[[event allTouches] allObjects] objectAtIndex:0] locationInView:self.button];  

    NSLog(@"pt.x=%f, pt.y=%f", pt.x, pt.y);  

}  

        这样就实现了事件的预处理,固有的事件处理机制也没有破坏,这个预处理是静悄悄的进行的。当然,如果我需要把某些事件过滤掉,也只需在DPApplication的sendEvent:方法里面抛弃即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: