如何删除以编程方式创建的按钮?
什么是删除了程序创建针对这种情况,例如按钮的代码:如何删除以编程方式创建的按钮?
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
按钮,会是什么码?
行[[self.view viewWithTag:3] removeFromSuperview];
将得到带有标记3的按钮,然后将其删除。如果你有3个标签的多个按钮,通过它们只是循环,像这样:
while (UIView *aView = [self.view viewWithTag:3]) {
[aView removeFromSuperview];
}
太好了,谢谢! :) – 2012-08-02 01:41:23
没问题 - 很高兴能够提供帮助! – jrtc27 2012-08-02 10:39:16
我想更安全的方式是使用[button removeFromSuperview]
,这将自动释放内心看法后,它一直保留通过addSubView:
。
当然,你需要一种方法来检索正确的按钮,你可以
- 检索
viewWithTag:
- 保持
NSMutableArray
或它们的普通的C数组,如果你需要更快的速度
看到他标记了他们,并询问如何使用特定标记去除按钮,“viewWithTag:'是迄今为止最简单的方法。 – jrtc27 2012-08-01 23:38:02
1.'null'不是Objective-C - 它是'nil',并且2.这只会使指针指向按钮nil - 视图仍然会有它。另外,如果你没有保存引用,你甚至会将按钮设置为'nil'?你将不得不根据它的标签获得子视图,但是你没有提到它。 – jrtc27 2012-08-01 23:30:18
@ahmadalishafiee:我完全不明白你的意思 – Jack 2012-08-01 23:31:30
他删除了他的评论,所以这个帖子看起来对未来的观众来说很幽默。关于主题:我已经在下面发布了一个答案 - 如果您有任何问题,请告诉我。 – jrtc27 2012-08-01 23:39:05