MrShoot
MrShoot

Reputation: 863

UILongPressGestureRecognizer not removing view

I'm not seeing what's wrong here. When user taps and hold, I add a view, when touch finishes the view gets removed. This does NOT work and I do see the UIGestureRecognizerStateEnded being sent.

However, if I call [tmpView removeFromSuperview]; outside of that state it gets removed without any issues.

Any idea what's causing this?

  -(void)longTapped:(UILongPressGestureRecognizer*)recognizer {
        UIView *tmpView = [[UIView alloc] init];
        tmpView.backgroundColor = [UIColor greenColor];

        // Position the menu so it fits properly
        tmpView.frame = CGRectMake(0, 100, 320, 250);

        // Add the menu to our view and remove when touches have ended
        if (recognizer.state == UIGestureRecognizerStateBegan) {
            [self.view addSubview:tmpView];
        }
        else if(recognizer.state == UIGestureRecognizerStateEnded){
            [tmpView removeFromSuperview];
        }
    }

Upvotes: 0

Views: 153

Answers (1)

RyanR
RyanR

Reputation: 7758

The second time your -longTapped: method is called it is instantiating a new instance of UIView in the tmpView variable, and trying to remove that from its superview. You need to store a reference to your added view on the controller when the long press starts, and when it ends you need to remove that object from its superview.

@interface myVC ()
@property (nonatomic, weak) UIView *tmpView;
@end

 -(void)longTapped:(UILongPressGestureRecognizer*)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        // Add the menu to our view and remove when touches have ended
        self.tmpView = [[UIView alloc] init];
        self.tmpView.backgroundColor = [UIColor greenColor];

        // Position the menu so it fits properly
        self.tmpView.frame = CGRectMake(0, 100, 320, 250);

        [self.view addSubview:self.tmpView];
    }
    else if(recognizer.state == UIGestureRecognizerStateEnded){
        [self.tmpView removeFromSuperview];
        self.tmpView = nil;
    }
}

Upvotes: 2

Related Questions