繁体   English   中英

iOS:随机模式并非在每个循环中都有效

[英]iOS: Random does not work in every loop

这就是我的iOS程序的目的。 按下开始按钮后,企鹅的随机图像将从右侧出现,向左移动并消失,然后一次又一次地重复,而无需再次按下开始按钮。 我试图在每个周期中显示一组不同的企鹅。 它确实会循环,但是,每个周期它仍显示相同的企鹅。 当我按下开始按钮,但只想按一次按钮时,它只会更改为其他企鹅,当循环继续进行时,每个循环中都会出现不同的企鹅。 我将随机代码放入循环中,但是我看不到它会随机化每个循环,它只会在每次按下开始按钮时才随机化。 任何想法如何解决?

-(IBAction)start:(id)sender {
[UIView animateKeyframesWithDuration:3 delay:0 options:UIViewKeyframeAnimationOptionRepeat animations:^{
    [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.3 animations:^{
    NSArray *imageNameArray = [[NSMutableArray alloc] initWithObjects:@"Right.png", @"Left.png", @"Straight.png", nil];
    Penguin.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])]];
    Penguin.center = CGPointMake(294, 373);
    Penguin.alpha = 1;
    Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}];
    [UIView addKeyframeWithRelativeStartTime:0.3 relativeDuration:0.4 animations:^{
    Penguin.center = CGPointMake(Penguin.center.x - 200, Penguin.center.y);}];
    [UIView addKeyframeWithRelativeStartTime:0.7 relativeDuration:0.3 animations:^{
    Penguin.alpha = 0;
    Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}];
    }completion:nil
    ];
    }

我认为重复动画的所有参数都只能设置一次,因此随机图像只能被拾取一次。 无需制作重复的动画,而是从动画的完成块调用start:方法,然后在动画方法之外进行随机选择,

-(IBAction)start:(id)sender {

    NSArray *imageNameArray = [[NSMutableArray alloc] initWithObjects:@"Right.png", @"Left.png", @"Straight.png", nil]; // There's no need to define this every time the method is called. It would be better to make this a property, and define it outside this method
    Penguin.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])]];

    [UIView animateKeyframesWithDuration:3 delay:0 options:0 animations:^{
        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.3 animations:^{

            Penguin.center = CGPointMake(294, 373);
            Penguin.alpha = 1;
            Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}];
        [UIView addKeyframeWithRelativeStartTime:0.3 relativeDuration:0.4 animations:^{
            Penguin.center = CGPointMake(Penguin.center.x - 200, Penguin.center.y);}];
        [UIView addKeyframeWithRelativeStartTime:0.7 relativeDuration:0.3 animations:^{
            Penguin.alpha = 0;
            Penguin.center = CGPointMake(Penguin.center.x - 40, Penguin.center.y);}];
    }completion:^(BOOL finished) {
        [self start:nil];
    }
     ];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM