0

我没有看到这里有什么问题。当用户点击并按住时,我添加一个视图,当触摸完成时,视图被删除。这不起作用,我确实看到 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];
        }
    }
4

1 回答 1

2

第二次调用 -longTapped: 方法时,它会在 tmpView 变量中实例化 UIView 的新实例,并尝试将其从其父视图中删除。当长按开始时,您需要在控制器上存储对添加视图的引用,当长按结束时,您需要从其父视图中删除该对象。

@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;
    }
}
于 2013-10-15T19:46:13.597 回答