Touch event not working? in UImageview?

I did the following in viewdidload viewcontroller.m

    img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
img.multipleTouchEnabled = YES;
[self.view addSubview:img];
[img release];

but Touchbegan, click Moved, everything doesn't work when I check the breakpoint? instead, when I use the XIB file, I set multipleTouchEnabled, but in both cases the touch event does not work ... anyHelp? you are welcome?

+2
source share
1 answer

You should try setting this property:

img.userInteractionEnabled = YES;

But this is not enough, because the methods:

touchesBegan:withEvent:touchesMoved:withEvent:touchesEnded:withEvent:

belong to the UIResponder class (the UIVIew base class), and not to the UIViewController.

So, if you want to be called, you must define a subclass of the UIView class (or UIImageView in your case), where you override the base methods.

Example:

MyImageView.h

@interface MyImageView : UIImageView {
}

@end

MyImageView.m

@implementation MyImageView

- (id)initWithFrame:(CGRect)aRect {
    if (self = [super initWithFrame:rect]) {
        // We set it here directly for convenience
        // As by default for a UIImageView it is set to NO
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // Do what you want here
    NSLog(@"touchesBegan!");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Do what you want here
    NSLog(@"touchesEnded!");
}

@end

MyImageView :

img = [[MyImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[self.view addSubview:img];
[img release];

( , self.view userInteractionEnabled, YES, ).

+3

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


All Articles