通过单击iPhone中屏幕的任何部分隐藏视图

时间:2013-10-21 14:59:11

标签: iphone ios uiview

我有一个View是iphone app中主视图的subView我希望在显示subView并且用户点击屏幕的一部分时除了subView然后subView应该隐藏。

这是我得到的代码,但它没有隐藏它:

    UITapGestureRecognizer *tapGR;
tapGR = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)] autorelease];
tapGR.numberOfTapsRequired = 1;
[self.View addGestureRecognizer:tapGR];

// Add a delegate method to handle the tap and do something with it.

-(void)handleTap:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded) {
    // handling code
  [myViewSheet removeFromSuperView];

}
}

2 个答案:

答案 0 :(得分:0)

实施UIGestureRecognizerDelegate协议: .H:

@interface YourView : UIView<UIGestureRecognizerDelegate>

的.m:

@implementation YourView{
    UIView * subview;
}

...

    subview = [[UIView alloc]initWithFrame:CGRectMake(0, 200, 320, 200)];
    [self addSubview:subview];


    UITapGestureRecognizer *tapGR;
    tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tapGR.numberOfTapsRequired = 1;
    tapGR.delegate = self;
    [self addGestureRecognizer:tapGR];

...

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch 
{
    if (touch.view == subView) 
    {
        return NO;
    }
    else 
    {
        return YES; 
    }
}

答案 1 :(得分:0)

您可能需要在主视图上设置userInteractionEnabled = YES(您附加手势识别器的那个。)