samwize
samwize

Reputation: 27383

How to setup UIView touch handler without subclassing

How do I capture touch events such as - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event without subclassing a UIView nor using UIViewControllers.

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

Upvotes: 3

Views: 2011

Answers (4)

rraallvv
rraallvv

Reputation: 2943

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];

Upvotes: 1

bstahlhood
bstahlhood

Reputation: 2006

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.

Upvotes: 4

hotpaw2
hotpaw2

Reputation: 70743

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.

Upvotes: 0

user189804
user189804

Reputation:

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.

Upvotes: 1

Related Questions