Adding multiple UIButtons to an UIView

2019-08-02 19:41发布

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

4条回答
SAY GOODBYE
2楼-- · 2019-08-02 20:21

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);
查看更多
女痞
3楼-- · 2019-08-02 20:30

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);
查看更多
男人必须洒脱
4楼-- · 2019-08-02 20:37

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

查看更多
劫难
5楼-- · 2019-08-02 20:40

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];
查看更多
登录 后发表回答