在屏幕上随机移动一个对象
我试图animation一个UIButton在屏幕上随意移动不同的方向。 下面的代码是一种工作。 button将开始沿随机path移动,但是,它只是继续在A点和B点之间来回移动。
[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];
我怎样才能让它在每次改变方向时继续向一个新的随机点移动,而不是简单地来回移动?
谢谢!
尝试这个:
-(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]; }
只要在方法内部添加一个计数器(int)来检查它是否被执行超过1000次,如果要停止它…