按下时如何使按钮随机移动

时间:2014-10-11 17:06:06

标签: ios objective-c

我到处搜索试图找到答案,但我发现的任何答案都不适合我...... 我想在按下时更随机地制作一个按钮。 我知道这很简单,xcode没有解决任何问题。当我运行我的代码时,模拟器运行正常,除了按钮不移动的事实。 这是我使用的代码;

-(IBAction)Counter {
[self moveButton];

}

-(void)moveButton {
int xCo = arc4random() %200;
int yCo = arc4random() %200;
CGRect frame = Butoon2.frame;
frame.origin.x = xCo;
frame.origin.y = yCo;

[UIView beginAnimations:nil context:nil];

[UIView setAnimationDuration:0.001];
Butoon2.frame = frame;
[UIView commitAnimations];

}

非常感谢您的投入!

2 个答案:

答案 0 :(得分:0)

试试这个:

-(void)moveButton {
int xCo = arc4random() %200;
int yCo = arc4random() %200;
CGRect frame = Butoon2.frame;
frame.origin.x = xCo;
frame.origin.y = yCo;

[UIView animateWithDuration:0.001
                      delay:0
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^(void) {
                     Button2.frame = frame;
                 }
                 completion:nil];
}

答案 1 :(得分:0)

试试这个:

-(IBAction)Counter:(id)sender {
   [self moveButton];
}

-(void)moveButton {
   int xCo = arc4random() %(int)(self.view.frame.size.width-Butoon2.frame.size.width);
   int yCo = arc4random() %(int)(self.view.frame.size.height-Butoon2.frame.size.height);
   CGRect frame = Butoon2.frame;
   frame.origin.x = xCo;
   frame.origin.y = yCo;

   [UIView beginAnimations:nil context:nil];

   [UIView setAnimationDuration:0.001];
   self.Button2.frame = frame;
   [UIView commitAnimations];
}