删除关于touchevent的UIView

时间:2013-02-04 11:58:39

标签: iphone xcode4.5

我在当前UIView中添加UIViewController。我需要在屏幕上的任何位置触摸时移除UIView。我在UIButton中有一个UIView。但是,如果我点击UIButton,那么UIView也会被删除。

实际上我在UIView中添加了一个按钮(退出),点击该按钮时会关闭currentview并转到homeViewController。但是,如果我点击当前视图中除UIView上的按钮以外的任何位置,则应删除UIView。但在我的情况下,如果我点击按钮,则UIView也被移除。

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

}

2 个答案:

答案 0 :(得分:1)

您必须跟踪触摸的位置,这意味着您必须检查是否已按下按钮的框架。如果你点击了按钮的位置,即按钮的框架,那么不要调用removeFromSuperView。 else调用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];
}

}

答案 1 :(得分:0)

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

- (IBAction)backgroundTapped:(id)sender;

和.m文件

 - (IBAction)backgroundTapped:(id)sender {
        //remove your view here
    [logout removeFromSuperview];
    }