0

按下按钮时,我需要在 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;
}

谢谢你的帮助!

4

2 回答 2

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

你明白了……

于 2012-08-08T02:59:36.393 回答
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);
于 2012-08-08T02:39:35.600 回答