使用arc4random iOS设置坐标范围

时间:2012-08-08 02:31:06

标签: ios coordinates arc4random

按下按钮时,我需要在iPhone屏幕上随机放置UIButton。我可以成功地做到这一点,但我的UIButton有时会出现边缘切断。所以我的问题是,如何设置arc4random的坐标范围? (例如,仅从x:75 y:75到x:345 y:405。)如果有任何帮助,这是我的IBAction:

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

    anExampleButton.center = position;
}

感谢您的帮助!

2 个答案:

答案 0 :(得分: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;
}

如果原点位于按钮中间,请执行以下操作:

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

你明白了......

答案 1 :(得分:0)

这样的事情:

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);