Answer the question
In order to leave comments, you need to log in
Fill view with buttons?
I want to fill a UIView with buttons with random positions so that they don't intersect.
My idea:
-create the first button and place it in a random position
-fill the view with the rest of the buttons (<20) so that they don't intersect.
What I've done:
-(void)generateButtonsForView:(UIView *)view buttonCount:(int)count
{
//get size of main view
float viewWidth = view.frame.size.width;
float viewHeight = view.frame.size.height;
//set button at random position
UIButton *initialButton = [[UIButton alloc] initWithFrame:CGRectMake(arc4random() % (int)viewWidth, arc4random() % (int)viewHeight, buttonWidth, buttonHeight)];
[initialButton setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
[view addSubview:initialButton];
// set count to 20 - max number of buttons on screen
if (count > 20)
count = 20;
//fill view with buttons from initial button +- 10 pixels
for (int i=0;i<=count;i++)
{
//button
UIButton *otherButtons = [[UIButton alloc] init];
[otherButtons setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
...//have no idea what to do here
}
}
Answer the question
In order to leave comments, you need to log in
A little different than you want, but you can do this:
1. Saw the view into horizontal stripes with a height of 2 button heights + 10 points (you can play around). Make a gap of 5 points along the height between the stripes.
2. We divide each strip vertically into cells (the width of a button), select the horizontal distance between them randomly between 5-10, as a result, the cell has the width of the button and its double height.
3. The button is placed in a cell, the vertical position is chosen randomly. The total distance both vertically and horizontally will be more than 10, and horizontally more than 5 is guaranteed
4. Repeat for the rest of the strips (it's better to add a random initial horizontal offset for the buttons). As a result, between the "corresponding" buttons in adjacent strips there will be, in the worst case, 2 button heights + 25 points.
4 point is the only one that does not satisfy the condition. The whole thing can be optimized to ensure that the buttons in the stripes are pressed against their neighbor from above.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question