0

I need to randomly place a UIButton around the iPhone screen when a button is pressed. I can do this successfully, but my UIButton appears cut off on the edges sometimes. So my question is, how can I set a range of coordinates for arc4random to work with? (e.g. Only from x:75 y:75 to x:345 y:405.) If it's any help, here's my IBAction:

- (IBAction) stackOverflowExampleButtonPressed
{  
    CGPoint position;
    position.x = (arc4random() % (75)) + 345;
    position.y = (arc4random() % (75)) + 405;

    anExampleButton.center = position;
}

Thanks for any help!

Aaron Chapman
  • 44
  • 1
  • 9

2 Answers2

1
- (IBAction) stackOverflowExampleButtonPressed
{  
CGPoint position;
position.x = arc4random()%346 + 75;
position.y = arc4random()%406 + 75;

//it's random from 0 to 345 + 75 so when it's 0 coord= 75..when it's 345 coord =420

anExampleButton.center = position;
}

if you have the origin in the middle of the button just do something like:

position.x=arc4random()%(view.width-button.width)+button.width/2
position.x=arc4random()%(view.height-button.height)+button.height/2

you get the idea...

skytz
  • 2,201
  • 2
  • 18
  • 23
  • This works wonders. I don't know why I didn't think about it. Thank you ever so much. – Aaron Chapman Aug 10 '12 at 01:20
  • Instead of `arc4random()%346` `use arc4random_uniform(346)` which will provide a non-biased result. `arc4random_uniform` is available in Mac 10.7 and iOS 4.3 and above. – zaph Sep 16 '12 at 16:13
0

Something like this :

float x = 75 + rand() % (345 - 75 - anExampleButton.frame.width);
float y = 75 + rand() % (405 - 75 - anExampleButton.frame.height);
anExampleButton.frame = CGRectMake(x, y, anExampleButton.frame.width, anExampleButton.frame.height);
Tutankhamen
  • 3,532
  • 1
  • 30
  • 38