Ios:UIButton颜色会随着持续时间自动变化

时间:2012-07-17 05:27:58

标签: ios

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

关心, 拉杰什

1 个答案:

答案 0 :(得分:3)

您可能会觉得这很有帮助,此代码段每隔3.5秒就会在random处选择一种颜色,并将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];
}