xcode 如何删除以编程方式创建的按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11768987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete buttons that was created programmatically?
提问by Fernando Pérez Guzmán
What would be the code to delete buttons that was created programmatically for this case for example:
例如,删除以编程方式为这种情况创建的按钮的代码是什么:
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];
}
Let's say that I want to delete the button with tag = 3
, what would be the code?
假设我想用 删除按钮tag = 3
,代码是什么?
回答by jrtc27
The line [[self.view viewWithTag:3] removeFromSuperview];
would get the button with tag 3 and then remove it. If you have multiple buttons with a tag of 3, just loop through them like so:
该行将[[self.view viewWithTag:3] removeFromSuperview];
获取带有标签 3 的按钮,然后将其删除。如果您有多个标签为 3 的按钮,只需像这样循环遍历它们:
while (UIView *aView = [self.view viewWithTag:3]) {
[aView removeFromSuperview];
}
回答by Hyman
I guess the safer way would be to use [button removeFromSuperview]
, this will automatically release the inner view after that it has been retained by addSubView:
.
我想更安全的方法是使用[button removeFromSuperview]
,这将在内部视图被addSubView:
.
Of course you'll need a way to retrieve the correct button, you could
当然,您需要一种方法来检索正确的按钮,您可以
- retrieve it
viewWithTag:
- keep a
NSMutableArray
or a plain C array of them if you need more speed
- 取回它
viewWithTag:
NSMutableArray
如果您需要更高的速度,请保留一个或一个普通的 C 数组