2011-05-24 60 views
1

我已經創建了一個按鈕是動態的,現在我想設置按鈕的特定索引的背景。如何在iPhone中爲按鈕的特定索引設置背景圖片?

這裏我的示例代碼段,

在接口文件,

UIButton *answerBtn; 
@property (nonatomic, retain) UIButton *answerBtn; 


for(int i = 0; i < [myArray count]; i++) { 

    answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

[answerBtn setFrame:CGRectMake(30, x, 260, 40)]; 

answerBtn.tag = i; 

[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal]; 

[self.view addSubview: answerBtn]; 

} 

在我的情況我想設置在不同的方法按鈕背景。

-(void) custom Method 
{ 
    if(indexValue == correctIndex) // Values are 2 
    { 
    // so i want to set the background image for the second button 

     [answerBtn setBackgroundImage:[UIImage imageNamed:@"selected_correct_answer.png"] forState:UIControlStateNormal]; 

    } 
} 

但它不設置相應的指標,所以我該怎麼辦呢? [在這裏輸入的形象描述] [1]

回答

2

試試這個

for(int i = 0 ; i < [myArray count] ; i++) 
{ 
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [btn setTag:i]; 
    [btn setFrame:CGRectMake(30, x, 260, 40)]; 
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:btn]; 
} 

- (IBAction) btnClicked::(id)sender 
{ 
    UIButton *btnTapped=(UIButton *)sender; 

for(UIView *btn in self.view.subviews) 
{ 
    if([btn isKindOfClass:[UIButton class]]) 
    { 
     UIButton *btnComp = (UIButton*)btn; 

     if(btnComp.tag == btnTapped.tag) 
      [btnComp setBackgroundImage:[UIImage imageNamed:@"selected_correct_answer.png" forState:UIControlStateNormal]; 
     else 
      [btnComp setBackgroundImage:[UIImage imageNamed:@"default_image.png" forState:UIControlStateNormal]; 


    } 


} 

}

0
UIButton *answerBtn = (UIButton *)[self objectWihTag:1] 
1

使用- (空)定製:(ID)發送代替- (無效)定製

在發件人你可以有按鈕的索引。

相關問題