11
votes

How to Align subviews trailing end to superviews center X axis using Autolayout in Storyboard?

I have one subview inside a superview and the requirement is to align subviews trailing end to superviews center on X axis.

I may be missing something in the documents but I know the workaround could be to place a invisible UIView of 1 point width at the center of the superview using the constraint Horizontal center in Container that will help me to align subviews trailing end to superview's center.

I am in search of any better way of doing it.

Thanks

2

2 Answers

27
votes

You can just change the constraint to align the trailing edge to the center - first create a normal horizontal centring constraint, and then edit that constraint to change the value to trailing for the subview.

enter image description here

enter image description here

enter image description here

0
votes

You can do it also programmatically.

addSubview(view)
view.trailingAnchor.constraint(equalTo: self.centerXAnchor).isActive = true