user339946
user339946

Reputation: 6119

Can't remove imageView from within UIGestureRecognizer?

I have a photo on the screen which when held, I want to display at full size. Here's the gesture recognizer:

        UILongPressGestureRecognizer *hold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(hold:)];
        hold.minimumPressDuration = 0;

        [self.photoImageView addGestureRecognizer:hold];

And here's the listener:

-(void)hold:(UILongPressGestureRecognizer *)sender{
    UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
    img.userInteractionEnabled = NO;

    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"state began");
        [self.view addSubview:img];
    } else if (sender.state == UIGestureRecognizerStateEnded){
        NSLog(@"state ended");
        [img removeFromSuperview];
    }
}

The image gets added to the screen correctly, however [img removeFromSuperview] does not seem to respond. Any reason for this happening? The NSLog for ending state is correctly firing off.

Upvotes: 0

Views: 129

Answers (2)

Ajay Chaudhary
Ajay Chaudhary

Reputation: 1991

You don't need to create new imageview in gesture's action. Just add or remove your self.photoImageView like this

-(void)hold:(UILongPressGestureRecognizer *)sender
{

    if(sender.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"state began");
        [self.view addSubview:self.photoImageView];
    }
     else if (sender.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"state ended");
        [self.photoImageView removeFromSuperview];
    }
}

Upvotes: -1

Marcin Kuptel
Marcin Kuptel

Reputation: 2664

It's because you are creating a new instance of UIImageView instead of removing the one that is displayed.

-(void)hold:(UILongPressGestureRecognizer *)sender{

    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"state began");

        UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
        img.tag = IMAGE_VIEW_TAG;
        img.userInteractionEnabled = NO;
        [self.view addSubview:img];

    } else if (sender.state == UIGestureRecognizerStateEnded){
        NSLog(@"state ended");
        UIImageView *img = [self.view viewWithTag: IMAGE_VIEW_TAG];
        [img removeFromSuperview];
    }
}

Upvotes: 2

Related Questions