如何在iPhone中设置按钮特定索引的背景图像?

时间:2011-05-24 12:09:45

标签: iphone image background uibutton

我已经动态创建了一个按钮,现在我想为按钮的特定索引设置背景。

这是我的示例代码段,

在界面文件中,

 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]

3 个答案:

答案 0 :(得分: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];


    }


}

}

答案 1 :(得分:1)

使用 - (void)自定义:(id)发件人而不是 - (void)自定义

在发件人中,您可以拥有该按钮的索引。

答案 2 :(得分:0)

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