Reputation: 13
I'm creating a very simple app for 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.
Upvotes: 0
Views: 7812
Reputation: 365
% 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)];
}
Upvotes: 1
Reputation: 7275
Using arc4random()
to generate a random number, you can generate an x and y coordinate to move the button to. 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)];
}
Upvotes: 5
Reputation: 1337
To generate random numbers Generating random numbers in Objective-C
To move yor uibutton
button.center= CGPointMake(xCoord, yCoord);
Upvotes: 2