How to remove the button tag duplicates in iPhone?
I have created buttons are programmatically and set the button tags.
View Did Load:
I have created one view and added the buttons are sub view into that view.
-(void) viewDidLoad
{
self.answerSubview = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 230)];
self.answerSubview.backgroundColor = [UIColor clearColor];
[self.view addSubview:answerSubview];
[self buttonCreation];
}
-(void) buttonCreation{
int x =100;
for(i = 开发者_如何学C0; i < 4; i++) {
UIButton *answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[answerBtn setFrame:CGRectMake(40, x, 260, 40)];
answerBtn.tag = ar[i];
[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal];
[self.answerSubview addSubview:answerBtn];
x = x+50;
}
}
And i want to set the background image for the certain index of the button, when the time is finished,
-(void) timerFinished
{
for (UIView* view in [self.answerSubview subviews]) {
if([view isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton*)view;
NSLog(@"button value %d", btn.tag);
if(btn.tag == correctIndex)
{
[btn setBackgroundImage:[UIImage imageNamed:@"selected_correct_answer.png"] forState:UIControlStateNormal];
}
}
}
}
But every time,the tag values are added into the stack,I have randomly generated numbers and set it into the button tags, so now it comes like, REsult:
First time, Second time,
0 0
1 1
3 3
2 2
3
1
2
0
(Actually my expected result is 3 1 2 0).
So how could i remove the previous tag values and get the correct tag values at a time.
Please help me out.
There are two things you can consider doing. Since the only thing that changes on every iteration is the text on the button. You could probably reuse them. Setup once and put them in ivars. On every iteration, change the text and tag of the button.
If that is not the route you're interested in, you can probably send removeFromSuperview
message to those four button objects.
However, the first method is a better approach in my opinion because it will do away with continuous creation-destruction cycle.
精彩评论