Search code examples
ioscoordinatesarc4random

Setting a range of coordinates with arc4random iOS


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!


Solution

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