UILongPressGestureRecognizer不删除视图

时间:2013-10-15 19:34:52

标签: iphone ios uiview uigesturerecognizer

我不知道这里有什么问题。当用户点击并按住时,我添加了一个视图,当触摸完成后,视图将被删除。这不起作用,我确实看到发送了UIGestureRecognizerStateEnded。

但是,如果我在该状态之外调用[tmpView removeFromSuperview];,则会将其删除而不会出现任何问题。

知道造成这种情况的原因是什么?

  -(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];
        }
    }

1 个答案:

答案 0 :(得分:2)

第二次调用你的-longTapped:方法时,它会在tmpView变量中实例化一个新的UIView实例,并试图从它的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;
    }
}