[英]How to move button to random position?
我正在为iPhone创建一个非常简单的应用程序。
只是不知道如何在触摸按钮时将其移动到随机位置(但在屏幕上)。
我正在使用Xcode 4.2。
使用arc4random()
生成随机数,您可以生成x和y坐标以将按钮移动到该坐标。 您需要考虑按钮的宽度和高度,以使其不会部分脱离屏幕,也要考虑屏幕的宽度和高度,以使其不会完全脱离屏幕。
-(void)buttonPressed:(id)sender {
UIButton *button = (UIButton *)sender;
int xmin = ([button frame].size.width)/2;
int ymin = ([button frame].size.height)/2;
int x = xmin + (arc4random() % (view.frame.size.width - button.frame.size.width));
int y = ymin + (arc4random() % (view.frame.size.height - button.frame.size.height));
[button setCenter:CGPointMake(x, y)];
}
%不适用于浮点数,因此最好将其更改为:
- (IBAction)buttonPress:(UIButton *)sender {
UIButton *button = (UIButton *)sender;
int xmin = ([button frame].size.width)/2;
int ymin = ([button frame].size.height)/2;
int x = xmin + arc4random_uniform(self.view.frame.size.width - button.frame.size.width);
int y = ymin + arc4random_uniform(self.view.frame.size.height - button.frame.size.height);
[button setCenter:CGPointMake(x, y)];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.