Reputation: 2308
In Android, when you add subviews to the horizontal LinearLayout, you would see that all the subviews would be aligned horizontally.
|subview1|subview2|subview3...
In iOS, how do I achieve this? I have a UIView as the parent view, but when I add subviews, it would get stack on top of each other. How do you use UIView.addSubView such that all the subviews would align horizontally?
One way, that I am attempting now is changing the frames.origin.x of each subviews for example
subview1.origin.x = 0
subview2.origin.x = subview1.origin.x + subview1.size.width
subview3.origin.x = subview2.origin.x + subview2.size.width
...
Is there better ways? thanks, and would appreciate any suggestions, or comments.
Upvotes: 1
Views: 2017
Reputation: 13127
As of iOS 9 you can use UIStackView
, which works very similarly to LinearLayout
: you add views and the stack view arranges them as needed based on your sizing option. If you're using Interface Builder you can experiment with each of the options to see which one suits your needs. You can also set spacing between views in the stack view, adding some padding.
For your particular needs, use stackView.axis = UILayoutConstraintAxisHorizontal;
to make your views line up horizontally.
WARNING: When adding stack view child views in code you should always use addArrangedSubview()
like this:
stackView.addArrangedSubview(someView)
If you try to use plain old addSubview()
it won't work correctly, because the stack view won't know to arrange it.
As for removing, you need to be careful to use stackView.removeArrangedSubview(someView)
and someView.removeFromSuperview()
otherwise the view won't be removed correctly.
You might find my UIStackView tutorial useful.
Upvotes: 0
Reputation: 10938
Either:
AutoLayout as suggest in another answer if using Interface Builder (Nibs or Storyboards).
AutoResizingMasks
by aligning them once and setting flexible top and bottom margins.
Manually by using UIView
's center
property.
CGFloat centerY = ...;
for (UIView * view in superview.subviews)
{
view.center = CGPointMake(view.center.x, centerY);
}
Upvotes: 1
Reputation: 2131
Yes, u r doing in right direction - you will have to change view's frame manually. there are convinient API for that:
subview1.origin.x = 0
subview2.origin.x = CGRectGetMaxX(subview1.frame);
subview3.origin.x = CGRectGetMaxX(subview2.frame);
Take into consideration that constraints are available form ios 6.0
Upvotes: 2
Reputation: 33359
Using the Auto Layout feature, which can be done from the interface builder GUI, or else programatically:
Upvotes: 2