2011-02-17 16 views
5

Estoy tratando de animar un UIButton para mover aleatoriamente alrededor de la pantalla en diferentes direcciones. El siguiente código está funcionando. El botón comenzará a moverse a lo largo de un camino al azar, sin embargo, a continuación, sólo continúa moviéndose hacia atrás y adelante entre el punto A y el punto B.Mover un objeto al azar alrededor de la pantalla

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:1]; 
[UIView setAnimationRepeatCount:1000]; 
[UIView setAnimationRepeatAutoreverses:YES]; 

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); 
button.center = squarePostion; 

[UIView commitAnimations]; 

¿Cómo puedo conseguir que se mantienen en movimiento a un nuevo punto al azar cada vez cambia de dirección, en lugar de simplemente moverse hacia adelante y hacia atrás?

Gracias!

Respuesta

7

probar esto:

-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { 

     [UIView beginAnimations:nil context:nil]; 
     [UIView setAnimationDuration:1]; 
// remove: 
     // [UIView setAnimationRepeatCount:1000]; 
     // [UIView setAnimationRepeatAutoreverses:YES]; 

     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); 
     button.center = squarePostion; 
// add: 
    [UIView setAnimationDelegate:self]; // as suggested by @Carl Veazey in a comment 
     [UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)]; 

     [UIView commitAnimations]; 
    } 

y simplemente añadir un contador (int) dentro del método para comprobar si se ejecuta más de 1000 veces, si quieres pararlo ...

+0

El botón sólo se trasladó a punto B y luego parado. – thenameisnick

+2

Es posible que deba agregar [UIView setAnimationDelegate: self]; allí también. –

+1

Funciona muy bien. ¡Gracias! – thenameisnick

Cuestiones relacionadas