如何在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]     

解决方法

尝试这个
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];


    }


}
}     ,使用-(void)custom:(id)sender而不是-(void)custom。 在发送者中,您可以获取按钮的索引。     ,
UIButton *answerBtn = (UIButton *)[self objectWihTag:1]