Steven Steven - 5 months ago 23
Objective-C Question

Touch method UIImageView inside UIScrollView

I am wondering how I can use a touch method for a

UIImageView
inside a
UIScrollView
in xCode.
When I add the
UIImageView
subview to the self.view, I can use the touch method. But when I add the UIImageView subview to the UIScrollView, I can't. How can I solve this?

This is my code:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
touches = [event allTouches];
for (UITouch *touch in touches) {

NSLog(@"Image Touched");
}
}

- (void)viewDidLoad
{
[super viewDidLoad];

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.9)];
scrollView.scrollEnabled = TRUE;
scrollView.bounces = TRUE;
scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
scrollView.userInteractionEnabled = YES;
[self.view addSubview:scrollView];

UIImageView *ImageView = [UIImageView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width * 0.04, 10, [UIScreen mainScreen].bounds.size.width * 0.28, [UIScreen mainScreen].bounds.size.height * 0.22)];
ImageView.image = [UIImage imageNamed(@"image.png")];
ImageView.layer.borderColor = [UIColor whiteColor].CGColor;
ImageView.layer.borderWidth = 1;
ImageView.userInteractionEnabled = YES;
[scrollView addSubview:ImageView];
}

Answer

Give UIGestureRecognizers a try. They are far easier to manage with multiple layers of touch management.

- (void)touchedImage:(UITapGestureRecognizer *)gesture {
    // When the gesture has ended, perform your action.
    if (gesture.state == UIGestureRecognizerStateEnded) {
        NSLog(@"Touched Image");
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.9)];
    scrollView.scrollEnabled = TRUE;
    scrollView.bounces = TRUE;
    scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    scrollView.userInteractionEnabled = YES;
    [self.view addSubview:scrollView];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width * 0.04, 10, [UIScreen mainScreen].bounds.size.width * 0.28, [UIScreen mainScreen].bounds.size.height * 0.22)];
    imageView.image = [UIImage imageNamed:@"image.png"];
    imageView.layer.borderColor = [UIColor whiteColor].CGColor;
    imageView.layer.borderWidth = 1;
    imageView.userInteractionEnabled = YES;
    [scrollView addSubview:imageView];

    // Create a tap gesture
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchedImage:)];
    [imageView addGestureRecognizer:tap];
}
Comments