ios - Arc4random 错误 : "Invalid operands to binary expression (' float' and 'float' )"

标签 ios uibutton arc4random

我想在特定 View 中的随机位置创建一个按钮。我搜索并阅读了一些 SO 主题,但是找不到解决问题的方法。

这是我的代码:

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect buttonRect = button1.frame;
buttonRect.size = CGSizeMake(100, 100);
button1.frame = buttonRect;

[self.arr addObject:button1];

int r = ([button1 frame].size.width)/2;

int x = r + (arc4random() % (self.view.frame.size.width - button1.frame.size.width));
int y = r + (arc4random() % (self.view.frame.size.height - button1.frame.size.height));
//ERROR:Invalid operands to binary expression ('float' and 'float')

[button1 setCenter:CGPointMake(x, y)]; 

最佳答案

mod (%) 不适用于 float 。

int x = r + (arc4random() % (int)(self.view.frame.size.width - button1.frame.size.width));
int y = r + (arc4random() % (int)(self.view.frame.size.height - button1.frame.size.height));

作为附加说明,arc4random() % ...not recommended .

这是首选方法:

int x = r + arc4random_uniform(self.view.frame.size.width - button1.frame.size.width);
int y = r + arc4random_uniform(self.view.frame.size.height - button1.frame.size.height);

关于ios - Arc4random 错误 : "Invalid operands to binary expression (' float' and 'float' )",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380844/

相关文章:

iOS在线广播流媒体问题

ios - UIVideoEditorController 始终在保存时压缩视频

ios - 调试 xcode 阶段?

objective-c - UIButton 子类 - 设置属性?

ios - arc4random_uniform() 的操作系统要求

objective-c - arc4random 和 % 运算符

objective-c - iOS 以编程方式从照片库中选择图片

ios - 点击时 UIButton 不显示任何效果?

ios - 快速访问 UIButton 的文本时出现奇怪的错误

iphone - iOS:如何生成 8 个唯一的随机整数?