2011-11-17 34 views

回答

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

%將無法在彩車工作,所以最好是將其更改爲:

- (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)]; 
} 
相關問題