Stefan
Stefan

Reputation: 29017

Adding multiple UIButtons to an UIView

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

Upvotes: 1

Views: 13092

Answers (4)

Ron Srebro
Ron Srebro

Reputation: 6862

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

Upvotes: 4

Stefan
Stefan

Reputation: 29017

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...

Upvotes: 0

teabot
teabot

Reputation: 15444

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

Upvotes: 3

Ron Srebro
Ron Srebro

Reputation: 6862

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

Upvotes: 2

Related Questions