سؤال

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!

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top