views:

3273

answers:

4

Hi,

I've added some buttons to an UIView (via addSubview) programmatically. However, they appear as overlays (so that I always see the last button only). How do I add new buttons below existing buttons?

Regards

+2  A: 

Set the UIView's frame origin to layout the UIButtons in the locations you wish:

CGRect buttonFrame = button.frame;
buttonFrame.origin = CGPointMake(100.0f, 100.0f);
button.frame = buttonFrame;
view.addSubview(button);
teabot
You'll need to add "button.frame = buttonFrame;" after line 2 or 3 to make this work. Otherwise, you're just modifying a copy of the frame rectangle.
e.James
@eJames - Good call
teabot
+1  A: 

You can either use the insertSubview:atIndex method or insertSubview:belowSubview of your view.

UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,100,100)];

[myView insertSubview:myButton belowSubview:previousButton];

OR

[myView insertSubview:myButton atIndex:0];
Ron Srebro
I was uncertain whether Stefan was referring to the Y or Z axis - but between us we have covered both.
teabot
Couldn't really figure that out either, but like you said we took care of both.
Ron Srebro
A: 

Thanks for your answers guys.

I did the (horizontal) align with this code:

if([myContainer.subviews lastObject] == nil){
  NSLog(@"NIL");
  [myContainer insertSubview:roundedButton atIndex:0];
 }else{
  [myContainer insertSubview:roundedButton belowSubview:[tagsContainer.subviews lastObject]];
 }

It works technically, but still overlays the buttons. I have to find a way, how to not overlay them...

Stefan
What do you mean overlay the buttons?
Ron Srebro
They appear visually as one button, because the are still on the same position (0.0, 0.0). So, my aim is to get the new starting position from the previous UIButton ([myContainer.subviews lastObject]). I think it has something to do with the UIButtons frame. But I don't know, how to get the positions.
Stefan
+1  A: 

you can offset the button like this

int newX = previousButton.frame.origin.x + previousButton.frame.size.width ;
int newY = previousButton.frame.origin.y ;

and either set the frame for new button when you create it:

[[UIButton alloc] initWithFrame:CGRectMake(newX,newY,100,100)];

or set the frame later

newButton.frame = CGRectMake(newX,newY,100,100);
Ron Srebro
What a coincidence, I made a similar solution at the same time ;-)Here is mine: roundedButton.frame = CGRectMake(previousFrame.origin.x + previousFrame.size.width + 5, 0, 200,30);Thanks!
Stefan