2

我想在某个视图中的随机位置创建一个按钮。我搜索并阅读了一些 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)]; 
4

2 回答 2

9
于 2013-08-22T12:49:24.843 回答
3

尝试改变

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

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

它可能会引发该错误,因为您正在尝试使用浮点数作为参数来计算模数

于 2013-08-22T12:47:36.000 回答