循环多种方法

时间:2012-11-27 01:59:55

标签: iphone ios

我制作了一个程序,可以在屏幕顶部的随机x坐标处生成图像。然后图像下降到底部。但是,我想每隔几秒钟继续生成新图像(同一图像),这样就好像同一图像的这些副本从顶部不断“下雨”。

如何让所有这些代码每0.5秒重复一次?

@implementation ViewController {

    UIImageView *_myImage;

}

- (void)viewDidLoad
{
    srand(time(NULL));e
    int random_x_coordinate = rand() % 286;
    CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
    UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
    [myImage setImage:[UIImage imageNamed:@"flake.png"]];
    myImage.opaque = YES;
    [self.view addSubview:myImage];
    _myImage = myImage;


    //FALLING BIRDS TIMER
    moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(moveObject) userInfo:nil repeats:YES];


}
    //FALLING BIRDS MOVER
-(void) moveObject {        // + means down and the number next to it is how many pixels y moves down per each tick of the TIMER above
        _myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
    }

1 个答案:

答案 0 :(得分:0)

只需将动画循环放在您在计时器上调用的方法中,例如

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                      target:self
                                                    selector:@selector(animate)
                                                    userInfo:nil repeats:YES];
    [timer fire];
}

- (void)animate
{
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.backgroundColor = color;
    [self.view addSubview:view];

    [UIView animateWithDuration:1.0 animations:^{
        view.frame = CGRectMake(0, 200, 50, 50);
    }];
}

会让你的方块从顶部连续下降。请记住定期清理未使用的视图以避免内存问题。