How to set up a UIView touch handler without a subclass

How to capture touch events, such as - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eventwithout subclassing UIView or using UIViewControllers.

What happens is that I have a simple UIView created programmatically and I need to identify the main events of the crane.

+3
source share
4 answers

If you are writing your application for iOS 4, use UIGestureRecognizer. Then you can do what you want. Recognize gestures without a subclass.

Otherwise, subclasses are the way to go.

+4
source

. , UIView, . , , , . , [super touchesBegan:touches] touchesBegan, .

+1

, UIView , - , ( ) / sendEvent: UIWindow.

+1

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

:

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

Source: https://habr.com/ru/post/1762224/


All Articles