2012-08-01 68 views
0

什麼是刪除了程序創建針對這種情況,例如按鈕的代碼:如何刪除以編程方式創建的按鈕?

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按鈕,會是什麼碼?

+0

1.'null'不是Objective-C - 它是'nil',並且2.這隻會使指針指向按鈕nil - 視圖仍然會有它。另外,如果你沒有保存引用,你甚至會將按鈕設置爲'nil'?你將不得不根據它的標籤獲得子視圖,但是你沒有提到它。 – jrtc27 2012-08-01 23:30:18

+0

@ahmadalishafiee:我完全不明白你的意思 – Jack 2012-08-01 23:31:30

+0

他刪除了他的評論,所以這個帖子看起來對未來的觀衆來說很幽默。關於主題:我已經在下面發佈了一個答案 - 如果您有任何問題,請告訴我。 – jrtc27 2012-08-01 23:39:05

回答

4

[[self.view viewWithTag:3] removeFromSuperview];將得到帶有標記3的按鈕,然後將其刪除。如果你有3個標籤的多個按鈕,通過它們只是循環,像這樣:

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

太好了,謝謝! :) – 2012-08-02 01:41:23

+0

沒問題 - 很高興能夠提供幫助! – jrtc27 2012-08-02 10:39:16

0

我想更安全的方式是使用[button removeFromSuperview],這將自動釋放內心看法後,它一直保留通過addSubView:

當然,你需要一種方法來檢索正確的按鈕,你可以

  • 檢索viewWithTag:
  • 保持NSMutableArray或它們的普通的C數組,如果你需要更快的速度
+0

看到他標記了他們,並詢問如何使用特定標記去除按鈕,「viewWithTag:'是迄今爲止最簡單的方法。 – jrtc27 2012-08-01 23:38:02

相關問題