如何通过单击按钮消失uiview

时间:2012-01-14 08:22:16

标签: iphone uiview uibutton

我以编程方式创建了一个解开按钮并进行了操作

{
UIButton *myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton1.frame = CGRectMake(20, 20, 80, 44); 
    [myButton1 setTitle:@"Click Me!" forState:UIControlStateNormal];
    [myButton1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton1];
}

在IBAction中我有一个像这样的子视图的UIView

- (IBAction)buttonClicked:(id)sender 
{
    CGRect myFrame = CGRectMake(0, 300, 100, 50);
    UIView *myView = [[UIView alloc] initWithFrame:myFrame];
    myView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:myView];
    [myView release];
}

我现在想要的是当用户第二次按myButton1时,子视图必须消失。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

您可以使用[view removeFromSuperView]方法删除视图。

答案 1 :(得分:2)

在我们的代码中做一些修正 -

**Action like this -** 

- (IBAction)buttonClicked:(id)sender 
 {
   UIView *myView;
   if([self.view viewWithTag:56])
   {
    [[self.view viewWithTag:56] removeFromSuperview];
  }
  else
  {
   CGRect myFrame = CGRectMake(0, 300, 100, 50);
   myView = [[UIView alloc] initWithFrame:myFrame];
   myView.backgroundColor = [UIColor lightGrayColor];
  [myView setTag:56];
  [self.view addSubview:myView];
  [myView release];
   }
}

答案 2 :(得分:1)

buttonClicked:方法更改为此。

- (void)buttonClicked:(id)sender 
{
UIView *myView;
if(myView=[self.view viewWithTag:1234])
{
    [myView removeFromSuperview];
}
else {
    CGRect myFrame = CGRectMake(0, 300, 100, 50);
    myView= [[UIView alloc] initWithFrame:myFrame];
    [myView setTag:1234];
    myView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:myView];
    [myView release];
}
[self.view setNeedsDisplay];
}

编辑:如果使用IBAction并且不使用Interface Builder,则读取效果不佳。