简体   繁体   English

如何将按钮移动到随机位置?

[英]How to move button to random position?

I'm creating a very simple app for iPhone. 我正在为iPhone创建一个非常简单的应用程序。

Just don't know how to make the button move to random position (but on the screen) when it's touched. 只是不知道如何在触摸按钮时将其移动到随机位置(但在屏幕上)。

I'm using Xcode 4.2. 我正在使用Xcode 4.2。

Using arc4random() to generate a random number, you can generate an x and y coordinate to move the button to. 使用arc4random()生成随机数,您可以生成x和y坐标以将按钮移动到该坐标。 You want to account for the width and height of the button so that it doesn't go partially off screen, and also for the screen width and height so it doesn't go fully offscreen. 您需要考虑按钮的宽度和高度,以使其不会部分脱离屏幕,也要考虑屏幕的宽度和高度,以使其不会完全脱离屏幕。

-(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)];
}

To generate random numbers Generating random numbers in Objective-C 生成随机数在Objective-C中生成随机数

To move yor uibutton 移动您的uibutton

button.center= CGPointMake(xCoord, yCoord);

% won't work on floats so it is better to change this to: %不适用于浮点数,因此最好将其更改为:

- (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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM