0

I want a random frame.origin.x and frame.origin.y on each button click. The button need's to move inside of the iPhone screen.

CGRect frame = MyButton.frame;

frame.origin.x = 10;
frame.origin.y = 10;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.1];
MyButton.frame = frame;
[UIView commitAnimations];

Does anyone know how i can generate a random number/position? Something like

frame.origin.x = frame.size.width * (arc4random() % (10 - 1)); ?

But this is moving the button outside the screen

Frenck
  • 6,514
  • 5
  • 22
  • 25

2 Answers2

0

You have to define

#define ARC4RANDOM_MAX      0x100000000

And get the float like:

double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);

More information here

http://iphonedevelopment.blogspot.com/2008/10/random-thoughts-rand-vs-arc4random.html

LuisEspinoza
  • 8,508
  • 6
  • 35
  • 57
0

Just make a random floating-point value between 0 and 1 like in this question. Your current code will generate a value between 0 and 8 times the width of the screen, but only at integer multiples.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266