簡體   English   中英

如何將按鈕移動到隨機位置?

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

生成隨機數在Objective-C中生成隨機數

移動您的uibutton

button.center= CGPointMake(xCoord, yCoord);

%不適用於浮點數,因此最好將其更改為:

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