首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用arc4random iOS设置坐标范围

使用arc4random iOS设置坐标范围
EN

Stack Overflow用户
提问于 2012-08-08 10:31:06
回答 2查看 414关注 0票数 0

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

代码语言:javascript
运行
复制
- (IBAction) stackOverflowExampleButtonPressed
{  
    CGPoint position;
    position.x = (arc4random() % (75)) + 345;
    position.y = (arc4random() % (75)) + 405;

    anExampleButton.center = position;
}

谢谢你的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-08 10:59:36

代码语言:javascript
运行
复制
- (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;
}

如果在按钮中间有原点,只需执行以下操作:

代码语言:javascript
运行
复制
position.x=arc4random()%(view.width-button.width)+button.width/2
position.x=arc4random()%(view.height-button.height)+button.height/2

你明白我的意思了吧。

票数 1
EN

Stack Overflow用户

发布于 2012-08-08 10:39:36

如下所示:

代码语言:javascript
运行
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11856872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档