1

我是一个新的 iPhone 程序员。我想知道如何以特定的时间间隔自动更改 UIButton 颜色。

问候, 拉杰什

4

1 回答 1

3

您可能会发现这很有帮助,此代码段random每 3.5 秒选择一种颜色,并将其backgroundColor从当前状态变为新颜色。

- (void)viewDidLoad
{       
[super viewDidLoad];

    NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval: 3.5
                                target: self
                                selector: @selector (updateBackgroundColor)
                                userInfo: nil
                                repeats: YES]];

}
- (void) updateBackgroundColor {

    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationDuration: 3.0];

    CGFloat redLevel    = rand() / (float) RAND_MAX;
    CGFloat greenLevel  = rand() / (float) RAND_MAX;
    CGFloat blueLevel   = rand() / (float) RAND_MAX;

    myButton.backgroundColor = [UIColor colorWithRed: redLevel
                                                green: greenLevel
                                                 blue: blueLevel
                                                alpha: 1.0];
    [UIView commitAnimations];
}
于 2012-07-17T05:38:04.860 回答