简体   繁体   中英

how to add subviews next to each other in code?

I am trying to add subviews to window that will be placed next to each other, on window resize they will be resized and stay next to each other, I am adding the subviews in code using

NSWindow* window;
[window.contentFrame addSubView:newView];

i would like to do so with the constraints API:

contentView addConstraint:[NSLayoutConstraint constraintWithItem:prevView
                                                                     attribute:?
                                                                     relatedBy:?
                                                                        toItem:newView
                                                                     attribute:NSLayoutAttributeLeft
                                                                    multiplier:?
                                                                      constant:?]];

If you want to work on iOS 9 or later than the best way to achieve your goal to add subviews next to each other whether it is vertical or horizontal, is to use the UIStackView.

Class reference of UIStackView & Tutorial of UIStackView

You generally should not add views directly to the window. You should almost always have a view controller and you should be adding views to it's content view, not the window.

If you want to place your views side-by-side then you need to add auto-layout constraints to your views and then invoke layoutIfNeeded.

Explaining how to set up constraints is beyond the scope of an SO answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM