2

I want to create a button at random position in certain view. I searched and read some SO topics however I couldn't find the solution for my problem.

Here is my code:

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)]; 
Amar
  • 13,202
  • 7
  • 53
  • 71
THO
  • 105
  • 1
  • 14
  • possible duplicate of [How to make a modulo operation in objective-c / cocoa touch?](http://stackoverflow.com/questions/1271102/how-to-make-a-modulo-operation-in-objective-c-cocoa-touch) – kovpas Aug 22 '13 at 12:48
  • `width` is `CGfloat` so you are getting error. – Exploring Aug 22 '13 at 12:49

2 Answers2

9

mod (%) doesn't work on floats.

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

As an additional note, arc4random() % … is not recommended.

Here is the preferred method:

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);
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
3

try changing

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

to

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

It probably throws that error because you are trying to calculate modulus using a float as parameter

Daniel
  • 20,420
  • 10
  • 92
  • 149