在屏幕周围随机移动两个或多个对象

时间:2012-04-10 08:50:23

标签: iphone objective-c ios xcode

我正在尝试动画UIImageview在屏幕上随机移动。对于一个UIImageView它工作正常。但对于两个或更多对象,它无法正常工作。任何人都可以帮助我吗?

-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {          
    [UIView beginAnimations:nil context:nil];          
    [UIView setAnimationDuration:1];             
    CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);        
    CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);           
    CGPoint squarePostion = CGPointMake(x, y);         
    image.center = squarePostion;     
    [UIView setAnimationDelegate:self];       
    [UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
    [UIView commitAnimations];    
} 

提前致谢

1 个答案:

答案 0 :(得分:1)

最初,当您想要开始动画时,请按以下方式启动动画。

NSNumber *number1 = [NSNumber numberWithInt:0];
[UIView beginAnimations:nil context:number1];          
[UIView setAnimationDuration:2.0];             
CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);        
CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);           
CGPoint squarePostion = CGPointMake(x, y);         
imgView1.center = squarePostion;     
[UIView setAnimationDelegate:self];   
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
[UIView commitAnimations];    


number1 = [NSNumber numberWithInt:1];
[UIView beginAnimations:nil context:number1];          
[UIView setAnimationDuration:2.0];             
x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);        
y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);           
squarePostion = CGPointMake(x, y);         
imgView2.center = squarePostion;     
[UIView setAnimationDelegate:self];       
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
[UIView commitAnimations];    

您的animationLoop:finished:context:方法应如下所示。

-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {          
    [UIView beginAnimations:nil context:context];          
    [UIView setAnimationDuration:2.0];             
    CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);        
    CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);           
    CGPoint squarePostion = CGPointMake(x, y);   

    int i = [(NSNumber*)context intValue];
    if( i == 0 )
    {
        imgView1.center = squarePostion;    
    }
    else
    {
        imgView2.center = squarePostion;    
    }
    [UIView setAnimationDelegate:self];       
    [UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
    [UIView commitAnimations];    
} 

如上所述进行更改并尝试。你会得到你所需要的。