Reputation: 9390
I have created buttons dynamically and now I want to set the background for a particular index of the buttons.
Here is my sample snippet:
In the interface file:
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];
}
In my case, I want to set the button background in different methods.
-(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];
}
}
But it doesn't set the corresponding index, so how can I do that?
Upvotes: 1
Views: 613
Reputation: 547
Try this
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];
}
}
}
Upvotes: 2
Reputation: 14113
Use -(void)custom:(id)sender instead of -(void)custom.
In the sender you can have the index of the button.
Upvotes: 1