2012-06-07 45 views
1

我在我的應用程序中使用了20個UIButton。我在click事件中設置了所有這些UIButton的背景圖像。所有這些UIButton都保存在NSMutableArray中。這裏是代碼。如何一次刪除多個UIButtons的背景圖片?

   saveBtn = [[NSMutableArray alloc] init]; 
      for (int i=0; i<20; i++) { 
      UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
      btn.frame = CGRectMake(spacex, spacey, 30.0, 30.0); 
      idx = arc4random()%[arr count]; 
      NSString* titre1 = [arr objectAtIndex:idx]; 
      [btn setTitle:titre1 forState:UIControlStateNormal]; 
      spacex = spacex + 30; 
      [saveBtn addObject:btn]; 
      [self.view addSubview:btn]; 
      } 

我不成功這裏是我的代碼。

UIButton *currentButton = (UIButton *)sender; 
UIImage * imgNormal = [UIImage imageNamed:@"subtabButton.png"]; 
[currentButton setBackgroundImage:imgNormal forState:UIControlStateNormal]; 
[currentButton setTitle:currentButton.titleLabel.text forState:UIControlStateNormal]; 

但這些20個UIButtons有3個UIButtons之間,我想,當玩家點擊這三個UIButtons之一,所有以前設置的背景圖像是從UIButtons.can刪除任何一個指導我怎樣才能做到這一點..提前。

+0

爲什麼不能遍歷所有的UIButtons?把他們放在一個陣列中,並在他們身上。 –

回答

5
for (UIButton *btn in yourArrayOfButtons) 
{ 
    [btn setBackgroundImage:[UIImage imageNamed:@"nameofmyimage"] forState:UIControlStateNormal]; 
} 

,或者如果你想刪除的圖像:

for (UIButton *btn in yourArrayOfButtons) 
{ 
    [btn setBackgroundImage:nil forState:UIControlStateNormal]; 
} 
+0

他想刪除圖像。 –

+0

他問如何做一個for循環遍歷他的按鈕。 –

+1

+1來對付減1.他確實要求刪除它是公平的。 – erran

2

創建它們時,將所有按鈕放入NSArray或NSMutableArray中。然後使用for-in循環,或使用簡單的for循環來更改所有這些背景的背景。

+0

+1你打敗了我。 –

+0

哈哈是啊,這個問題很簡單,你得靈活一點。 – melsam

+0

@melsam我已經將所有這些按鈕保存在NSMutablearray中。可以給出有關for循環的想法如何使用for循環刪除這些圖像.. – jamil

1

可能最好的方法是動態創建每個按鈕。將每個按鈕信息存儲到NSMutableArray中,然後執行for循環以刪除圖像。

[currentButton setBackgroundImage:nil forState:UIControlStateNormal]; 

將刪除按鈕的圖像。它很難幫助你,而不會看到你的按鈕是如何存儲在一個數組中的。

+0

@johan我已經將所有這些按鈕保存在NSMutablearray中..可以給出想法關於for循環如何刪除這些圖像使用for循環.. – jamil

+0

檢查我的更新 –

+0

它可以刪除UIButtons的所有以前的setbackgroundimage。? – jamil

1

從我的理解,你有20個按鍵,其中這些按鈕的3去除圖像的其他17

如果3控制這個功能在陣列中,我建議你將它從它中刪除,因爲循環你的按鈕陣列也將從3 main按鈕中刪除圖像。您可以使用tag來區分3個主要按鈕。你的按鈕操作應該看起來像這樣。

-(void)buttonPressed:(id)sender { 

     UIButton *button = (UIButton*)sender; 

     if(button.tag == 1001 || button.tag == 1002 || button.tag == 1003) { 

      for (UIButton *btn in buttonArray) { 
       [btn setBackgroundImage:nil forState:UIControlStateNormal]; 
      } 

     } 


} 

我可能會誤解你的需要,但這是我想出的。希望能幫助到你 !

+0

Thanx @skram保留代碼..確切地說它的作品對我來說.. .. – jamil