如何删除以编程方式创建的按钮?

时间:2012-08-01 23:24:59

标签: objective-c xcode button

删除为此案例编程创建的按钮的代码是什么,例如:

for (m=0; m<f;m++ )
    {
        numerodeboton=partenumero+m+1;
        //NSLog(@"crear boton2, %i", numerodeboton);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setBackgroundImage:[UIImage imageNamed:@"boton.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(notasCurso)forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[NSString stringWithFormat:@"Botón %d", numerodeboton] forState:UIControlStateNormal];
        button.frame = CGRectMake(espacioh+m*(h+d)-z + h/2, y + (l-1)*(v+d) + v/2, 1, 1);
        button.layer.cornerRadius = 30;
        button.clipsToBounds = YES;
        button.layer.borderColor=[UIColor blackColor].CGColor;
        button.layer.borderWidth=0.01f;
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        button.tag = numerodeboton;
        [UIView animateWithDuration:0.05*numerodeboton animations:^{
            button.frame = CGRectMake(espacioh+m*(h+d)-z, y + (l-1)*(v+d), h, v);
        }];
        [self.view addSubview:button];
    }

假设我要删除带tag = 3的按钮,代码是什么?

2 个答案:

答案 0 :(得分:4)

[[self.view viewWithTag:3] removeFromSuperview];会获得带有标记3的按钮,然后将其删除。如果你有多个标签为3的按钮,就像这样循环:

while (UIView *aView = [self.view viewWithTag:3]) {
    [aView removeFromSuperview];
}

答案 1 :(得分:0)

我想更安全的方法是使用[button removeFromSuperview],这会在addSubView:保留之后自动释放内部视图。

当然你需要一种方法来检索正确的按钮,你可以

  • 检索viewWithTag:
  • 如果您需要更快的速度,请保留NSMutableArray或其中的普通C数组
相关问题