Adding multiple UIButtons to an UIView

2019-08-02 20:16发布

问题:

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

回答1:

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


回答2:

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


回答3:

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


回答4:

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