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

0 uibutton uiview ios

我正在为iPhone创建一个非常简单的应用程序.

只是不知道如何让按钮在触摸时移动到随机位置(但在屏幕上).

我正在使用Xcode 4.2.

Col*_*gic 5

使用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)];
}
Run Code Online (Sandbox Code Playgroud)