开发者

How to setup UIView touch handler without subclassing

开发者 https://www.devze.com 2023-01-14 14:43 出处:网络
How do I capture touch events such as - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event without s开发者_运维知识库ubclassing a UIView nor using UIViewControllers.

How do I capture touch events such as - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event without s开发者_运维知识库ubclassing a UIView nor using UIViewControllers.

What happens is that I have a simple UIView created programmatically and I need to detect basic tap events.


If you are writing your app for iOS 4, use UIGestureRecognizer. You can then do what you want. Recognize gestures without subclassing.

Otherwise, subclassing is the way to go.


There's just no reason not to. If you subclass and add nothing it's just a UIView called by another name. All you are doing is intercepting those functions that you are interested in. Don't forget you can do [super touchesBegan:touches] inside your subclass' touchesBegan if you don't want to stop responders up the chain from getting those events too.


I don't why you don't want to use the normal method of subclassing a UIView to capture touch events, but if you really need to do something weird or sneaky, you can capture all events (including touch events) before they get sent down the view hierarchy by trapping/handling the sendEvent: method at the UIWindow level.


CustomGestureRecognizer.h

#import <UIKit/UIKit.h>

@interface CustomGestureRecognizer : UIGestureRecognizer
{
}

- (id)initWithTarget:(id)target;

@end

CustomGestureRecognizer.mm

#import "CustomGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>

@interface CustomGestureRecognizer()
{
}
@property (nonatomic, assign) id target;
@end

@implementation CustomGestureRecognizer

- (id)initWithTarget:(id)target
{
    if (self =  [super initWithTarget:target  action:Nil]) {
        self.target = target;
    }
    return self;
}

- (void)reset
{
    [super reset];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    [self.target touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];

    [self.target touchesMoved:touches withEvent:event];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent: event];

    [self.target touchesEnded:touches withEvent:event];
}
@end

Usage:

CustomGestureRecognizer *customGestureRecognizer = [[CustomGestureRecognizer alloc] initWithTarget:self];
[glView addGestureRecognizer:customGestureRecognizer];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号