Hi I have a list of buttons which I am displaying using for loop. I want to animate random button can any one help me. Here is the code which I am trying, with this code only last button is animating continuously.
-(void)arrangeFavouriteWords
{
[buttonsArray removeAllObjects];
buttonsArray = [[NSMutableArray alloc]init];
for(int i=0;i<count1;i++)
{
WordObject *favObj = [databaseArray objectAtIndex:i];
float height = [MainViewController calculateHeightOfTextFromWidth:favObj.wordName :fontValue : buttonWidth :UILineBreakModeCharacterWrap];
myButton = [[MyCustomButton alloc]initWithIdValue:favObj.wordName];
myButton.backgroundColor = [UIColor clearColor];
myButton.frame = CGRectMake(0,yCoordinate,buttonWidth,height);
myButton.tag = i;
[myButton.titleLabel setFont:fontValue];
[myButton setTitleColor:color forState:UIControlStateNormal];
[myButton setTitle:favObj.wordName forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(wordClicked:) forControlEvents:UIControlEventTouchUpInside];
myButton.contentHorizontalAlignment = NO;
[buttonsArray addObject:myButton];
[displayView addSubview:myButton];
[myButton release];
yCoordinate = yCoordinate + height;
}
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:(0.5) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
-(void)onTimer
{
int randomIndex = arc4random() % [buttonsArray count];
printf("\n the random index is :%d",randomIndex);
myButton.tag = randomIndex;
if(randomIndex == myButton.tag)
{
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.scale"];
theAnimation.duration=1.0;
//theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:1.25f];
theAnimation.toValue=[NSNumber numberWithFloat:1.0f];
[myButton.layer addAnimation:theAnimation forKey:@"transform.scale"];
}
}
This is your problem:
You see, when you have a pointer to an instance (in this case, a
UIButtonnamedmyButton), it holds only one instance at a time, which must be the “last button” that you describe. Instances in Objective-C (or any other language for that matter), do not magically morph into the object you expect them to be within the method they would be most convenient in. You need to actually assignmyButtonto a different instance, or reference that other instance instead.This is further complicated by the fact that you are setting, then immediately checking the same value (
.tag), which is akin to saying “X is now 3. If X is 3, then…”. You need a proper reference to every button, and some place to store them all (say, an NSArray). That way, you can use the random index to retrieve the button from the array withobjectAtIndex:.