我想在特定视图中的任意位置创建一个按钮。我搜索并阅读了一些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(%)不适用于浮点运算。
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() % …
。
以下是首选方法:
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);
尝试更改
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)));
它可能会抛出这个错误,因为您正试图使用浮点作为参数来计算模量