0

I'm adding a UIView in the current UIViewController. I need to remove a UIView when touched anywhere on the screen. I have a UIButton in the UIView. But if I click UIButton then also the UIView is removed.

Actually I have added a button(Signout) in UIView which when click should dismiss the currentview and go to homeViewController. But if I tap anywhere on the current view other than the button on UIView then UIView should be removed. But in my case if I click button then also UIView is removed.

logout= [[UIView alloc]initWithFrame:CGRectMake(210,lbllogin.frame.origin.y+lbllogin.frame.size.height, 80, 50)];
logout.backgroundColor = [UIColor yellowColor];
btnSignout = [UIButton buttonWithType:UIButtonTypeCustom];
[btnSignout addTarget:self 
                action:@selector(aMethod:)
      forControlEvents:UIControlEventTouchDown];
btnSignout = CGRectMake(0,0,80,13);
[logout addSubview: btnSignout];
[self.view addSubview:logout];


        UIButton *btnsignout=[[UILabel alloc]init];
        [lblsignout setFrame:CGRectMake(0, 0, 80, 13)];
        lblsignout.textAlignment = NSTextAlignmentLeft;
        lblsignout.backgroundColor = [UIColor clearColor];
        lblsignout .font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
        lblsignout.text=@"Sign out";

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [logout removeFromSuperview];

}
4

2 回答 2

1

您必须跟踪触摸的位置,这意味着您必须检查您是否已经点击了按钮的框架。如果您点击了按钮的位置,即按钮的框架,则不要调用 removeFromSuperView。否则调用 removeFromSuperView。

//pseudo code,not actual code
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

if( touches.x & touches.y is in button frame)
{
[logout removeFromSuperview];
}
else
{
[btnSignOut removeFromSuperview];
}

}
于 2013-02-04T12:05:59.340 回答
0

要添加此功能,您必须转到 InterfaceBuilder-identity 检查器 - 类并设置类 UIControl.然后通过 ctr-drag 将 ViewController 的主视图连接到您的 .h 文件并创建用于修饰 inside.like 的操作:

- (IBAction)backgroundTapped:(id)sender;

并在 .m 文件中

 - (IBAction)backgroundTapped:(id)sender {
        //remove your view here
    [logout removeFromSuperview];
    }
于 2013-02-04T12:07:25.667 回答