0

嗨,我有一个使用 for 循环显示的按钮列表。我想为随机按钮设置动画,任何人都可以帮助我。这是我正在尝试的代码,此代码只有最后一个按钮连续动画。

 -(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"];
       }
   }
4

2 回答 2

0

这是你的问题:

    myButton.tag = randomIndex;
   if(randomIndex == myButton.tag)

您会看到,当您有一个指向实例的指针(在本例中为UIButtonnamed myButton)时,它一次只包含一个实例,它必须是您描述的“最后一个按钮”。Objective-C(或任何其他语言)中的实例不会神奇地变成您希望它们在最方便的方法中的对象。您需要实际分配myButton给不同的实例,或引用该实例其他实例代替。

由于您正在设置,然后立即检查相同.tag值(您需要正确引用每个按钮,以及将它们全部存储的地方(例如,一个 NSArray)。这样,您可以使用随机索引从数组中检索按钮。objectAtIndex:

于 2012-08-03T06:23:42.057 回答
0

你的myButton方法-onTimer是什么?我想最好从您那里获取对象buttonsArray并使用它:...

int randomIndex = arc4random() % [buttonsArray count];
UIButton *animatableButton = [buttonsArray objectAtIndex:randomIndex];

...

于 2012-08-03T06:24:46.367 回答