[英]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: 我想使用约束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. 如果你想在iOS 9或工作晚于最好的方式来实现自己的目标添加子视图彼此相邻无论是垂直或水平,是使用UIStackView。
Class reference of UIStackView & Tutorial of UIStackView UIStackView的类参考和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. 如果要并排放置视图,则需要向视图添加自动布局约束,然后调用layoutIfNeeded。
Explaining how to set up constraints is beyond the scope of an SO answer. 解释如何设置约束超出了SO答案的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.