2011-11-17 81 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)]; 
}