iphone - Set Uibutton Random Position on UIView -
i want set 5 buttons on uiview @ random position. buttons need maintain spacing each other. mean buttons should not overlap each other. buttons set on uiview come corners rotation animation.
btn1.transform = cgaffinetransformmakerotation(40); btn2.transform = cgaffinetransformmakerotation(60); btn3.transform = cgaffinetransformmakerotation(90); btn4.transform = cgaffinetransformmakerotation(30); btn5.transform = cgaffinetransformmakerotation(20);
i can rotate buttons using above code can pls. me set buttons on random position out overlapping each other. if points fix can set buttons animation code want random position of buttons.
[animationview movebubble:cgpointmake(18, 142) duration:1 : btn1]; [animationview movebubble:cgpointmake(118, 142) duration:1 : btn2]; [animationview movebubble:cgpointmake(193, 142) duration:1 : btn3]; [animationview movebubble:cgpointmake(18, 216) duration:1 : btn4];
thanks in advance.
1st, add buttons nsarray, make things easier:
nsarray *buttonarray = @[btn1,btn2,btn3,btn4,btn5];
now, code tries arrange them @ random positions.
int xtemp, ytemp; (int = 0; < 5; i++) { while (yes) { xtemp = arc4random_uniform(view.frame.size.width - [buttonarray[i] frame].size.width); ytemp = arc4random_uniform(view.frame.size.height - [buttonarray[i] frame].size.height); if (![self positionx:xtemp y:ytemp intersectsanybuttontillindex:i inbuttonarray:buttonarray]) { [animationview movebubble:cgpointmake(xtemp, ytemp) duration:1 : buttonarray[i]]; break; } } }
implement function somewhere too:
- (bool) positionx:(int)xtemp y:(int)ytemp intersectsanybuttontillindex:(int)index inbuttonarray:(nsarray *)buttonarray { //again please change < <= , i'm sorry, doing many things @ once. (int = 0; <= index; i++) { cgrect frame = [buttonarray[i] frame]; //edit : in logic earlier, had wrongly done minus should have done plus. if ((xtemp > frame.origin.x && xtemp < (frame.size.width + frame.origin.x)) && (ytemp > frame.origin.y && ytemp < (frame.size.height + frame.origin.y))) return yes; } return no;
ok workign soln., hope, added wolflink's answer. check this.
for (uibutton *button in buttonarray) { button.frame = cgrectmake(arc4random_uniform(view.frame.size.width - button.frame.size.width), arc4random_uniform(view.frame.size.height - button.frame.size.height), button.frame.size.width, button.frame.size.height); while ([self button:button intersectsbuttoninarray:buttonarray]) { button.frame = cgrectmake(arc4random_uniform(view.frame.size.width - button.frame.size.width), arc4random_uniform(view.frame.size.height - button.frame.size.height), button.frame.size.width, button.frame.size.height); } //another function -(bool)button:(uibutton *)button intersectsbuttoninarray:(nsarray *)array { (uibutton *testbutton in array) { if (cgrectintersectsrect(button.frame, testbutton.frame) && ![button isequal:testbutton]) { return yes; } } return no; }
Comments
Post a Comment