2011-02-17 94 views
5

我試圖讓UIButton在屏幕上以不同方向隨機移動。下面的代碼是有用的。該按鈕將開始沿隨機路徑移動,但是,那麼就繼續點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]; 

我怎樣才能得到它不斷地移動到每一次新的隨機點之間來回移動它改變方向,而不是簡單地來回移動?

謝謝!

回答

7

試試這個:

-(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次以上,如果想阻止它......

+0

按鈕只移到B點然後停下來。 – thenameisnick 2011-02-17 21:10:32