这是我的按钮创建功能。
-(void)buttonCreate {
//oneBtn5 Button
oneBtn5 = [UIButton buttonWithType:UIButtonTypeCustom];
oneBtn5.frame = CGRectMake(316, 389, 51, 21);
oneBtn5.tag = 5;
[oneBtn5 setTitle:@"" forState:UIControlStateNormal];
[oneBtn5 addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchDown];
[oneBtn5 setImage:[UIImage imageNamed:@"1c.png"] forState:UIControlStateNormal];
[self.view addSubview:oneBtn5];
}
我将使用viewonload(),
显示按钮- (void)viewDidLoad {
[super viewDidLoad];
[self buttonCreate];
}
这是我的重启功能,如果我点击重启,新按钮就会创建。
- (void)RestartAction {
[self buttonCreate];
}
我的问题是当我点击重启时如何删除重复按钮。它有办法解决这个问题。
答案 0 :(得分:0)
只需从其超级视图中删除按钮:
-(void)buttonCreate {
if (oneBtn5.superView) {
[oneBtn5 removeFromSuperview];
}
....
}
答案 1 :(得分:0)
-(void)buttonCreate {
//oneBtn5 Button
if (oneBtn5 != null)
[oneBtn5 removeFromSuperview];
oneBtn5 = [UIButton buttonWithType:UIButtonTypeCustom];
oneBtn5.frame = CGRectMake(316, 389, 51, 21);
oneBtn5.tag = 5;
[oneBtn5 setTitle:@"" forState:UIControlStateNormal];
[oneBtn5 addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchDown];
[oneBtn5 setImage:[UIImage imageNamed:@"1c.png"] forState:UIControlStateNormal];
[self.view addSubview:oneBtn5];
}
答案 2 :(得分:0)
你可以在buttonCreate中执行此操作
if(oneBtn5==nil)
{
oneBtn5 = [UIButton buttonWith....];
[self.view addsubview: oneBtn5;
}
按钮仅插入并添加一次
答案 3 :(得分:0)
将此用作:
-(void)buttonCreate {
if ([self.view.subviews containsObject:oneBtn5]) {
[oneBtn5 removeFromSuperview];
}
// YOUR CODE HERE
}
答案 4 :(得分:0)
如果是属性,就像人们告诉你的那样,检查它是否存在。
if(!self.oneBtn5){
//instance of button
self.oneBtn5 = [UIButton buttonWith....];
[self.view addsubview: self.oneBtn5];
}else{
//change stuff you need like text or frame
}
问题是您正在创建按钮的新实例,而不是重复使用前一个按钮。
答案 5 :(得分:0)
-(void)buttonCreate {
//oneBtn5 Button
if (oneBtn5 ){
[oneBtn5 removeFromSuperview];
oneBtn5=nil; // release the memory
}
oneBtn5 = [UIButton buttonWithType:UIButtonTypeCustom];
oneBtn5.frame = CGRectMake(316, 389, 51, 21);
oneBtn5.tag = 5;
[oneBtn5 setTitle:@"" forState:UIControlStateNormal];
[oneBtn5 addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchDown];
[oneBtn5 setImage:[UIImage imageNamed:@"1c.png"] forState:UIControlStateNormal];
[self.view addSubview:oneBtn5];
}
您必须在oneBtn = nil
之后写[oneBtn5 removeFromSuperview]
以释放先前创建的按钮的内存。当[oneBtn5 removeFromSuperview];
从超级视图中删除按钮但不释放内存。您必须通过将其设置为nil
来释放内存。