我使用for循环创建了五个按钮,效果很好。每当我点击重启按钮创建重复按钮
-(void)buttonCreate {
for( int i = 0; i < 5; i++ )
{
oneBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
oneBtn1.frame = CGRectMake(316,i*-5+474,51,50);
[oneBtn1 setTag:i];
[oneBtn1 addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchUpInside];
[oneBtn1 setImage:[UIImage imageNamed:@"1c.png"] forState:UIControlStateNormal];
[self.view addSubview:oneBtn1];
}
}
重启按钮功能:
-(void)restart {
[self buttonCreate];
}
我试过这个,但它只会删除5个中的一个按钮。
if(oneBtn1 != NULL) {
[oneBtn1 removeFromSuperview];
oneBtn1 = nil;
}
问题是:如何删除重复的按钮?
答案 0 :(得分:1)
创建一个数组(NSMutableArray *buttonHolderArray
)以保存所有五个按钮的出口。
[buttonHolderArray addObject:oneBtn1];
然后您可以根据需要删除/更新按钮。
一旦你不想要任何按钮,就清空阵列本身。除此之外,如果您想要清除视图,只需为所有按钮调用removeFromSuperView
I tried this one but it will remove only one button out of 5.
if(oneBtn1 != NULL) {
[oneBtn1 removeFromSuperview];
oneBtn1 = nil;
}
如果要删除所有按钮,则只删除一个按钮
for ( UIButton *button in buttonHolderArray){
button removeFromSuperView];
}
答案 1 :(得分:0)
在再次呼叫重新启动方法
之前使用此功能for (UIButton *btn in self.view.subviews ) {
[btn removeFromSuperview];
}
答案 2 :(得分:0)
在点击重启按钮之前,您可以从视图中删除调用方法removeChildViewsWithKindOfClass
-(void)restart {
[self.view removeChildViewsWithKindOfClass:[UIButton class]];
[self buttonCreate];
}
-(void)removeChildViewsWithKindOfClass:(Class)classToRemove{
if (classToRemove==nil) return;
for (UIView *v in [self subviews]) {
if ([v isKindOfClass:classToRemove]) {
[v removeFromSuperview];
}
}
}
如果要删除特定按钮,可以使用创建按钮时必须预先设置的属性tag
,并允许您删除带有特定标记的按钮。
答案 3 :(得分:0)
您可以通过检查按钮是否已创建来删除。
-(void)buttonCreate {
int tag_start = 500;
for( int i = 0; i < 5; i++ )
{
UIView * prevbtn = [self.view viewWithTag:tag_start + i];
if(prevbtn) {
[prevbtn removeFromSuperview];
}
oneBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
oneBtn1.frame = CGRectMake(316,i*-5+474,51,50);
[oneBtn1 setTag:tag_start + i];
[oneBtn1 addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchUpInside];
[oneBtn1 setImage:[UIImage imageNamed:@"1c.png"] forState:UIControlStateNormal];
[self.view addSubview:oneBtn1];
}
}