从SuperView中删除子视图的问题 - Objective-C

时间:2013-10-07 09:20:24

标签: objective-c views uigesturerecognizer subview

不确定为什么这不能从父视图中删除添加的子视图。如果longpress操作结束,我希望它被删除。我使用NSLog进行了测试,我知道手势正确地注册为已结束,但它并没有删除子视图。

-(void)addSubview:(UILongPressGestureRecognizer *)gesture {
    NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"overlayView" owner:self     options:nil];
    UIView *subView = [subviewArray objectAtIndex:0];

    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.view addSubview:subView];
        }
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [subView removeFromSuperview];
        }    
}

所需功能:

longpress启动:添加子视图。
longpress结束:删除子视图。

1 个答案:

答案 0 :(得分:5)

我希望您能通过在.h文件中声明UIView *子视图然后在viewDidLoad中添加以下行来解决此问题:

 NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"overlayView" owner:self     options:nil];
    UIView *subView = [subviewArray objectAtIndex:0];

然后:

-(void)addSubview:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.view addSubview:subView];
        }
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [subView removeFromSuperview];
        }    
}