Search code examples
iosiphonexcodeviewgesture-recognition

How to bring a view to the front on tapping them? ios


I am creating an instance of an image view every time a button is pressed. The last instance created is brought to the front. How do I bring a different instance to the front by tapping on it?

- (void) hatsPressed {
NSLog(@"HAT PRESSED");
hat2Image = [[UIImageView alloc] initWithFrame:CGRectMake(120, 50, 100, 100)];
hat2Image.image = [UIImage imageNamed:@"hat2"];
[self.view addSubview:hat2Image];
[self.view bringSubviewToFront:hat2Image];
hat2Image.userInteractionEnabled = YES;

UITapGestureRecognizer * recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    recognizer.delegate = self;
[hat2Image addGestureRecognizer:recognizer];
[hat2Image addGestureRecognizer:_hat2Pan];
[hat2Image addGestureRecognizer:_hat2Pinch];
[hat2Image addGestureRecognizer:_hat2Rotate];

}

Solution

  • The way I'd do it... Add a gesture recognizer to each of the image view you instantiate. The handler of that gesture needs to call a delegate method in the super view or controller where the image views are added to.

    When calling that delegate in your controller or view just call

    [self.view bringSubviewToFront:myTappedView];
    

    *I'd recycle the image views... creating one for each tap is not a very good way to do it.

    let me know if you need some more details.