How to center a subview of UIView

xonegirlz picture xonegirlz · Jun 28, 2012 · Viewed 144.7k times · Source

I have a UIView inside a UIViewm and I want the inner UIView to be always centered inside the outer one, without it having to resize the width and height.

I've set the struts and springs so that it's on top/left/right/bottom without setting the resize. But it still doesn't center. Any idea?

Answer

Hejazi picture Hejazi · Jun 29, 2012

You can do this and it will always work:

child.center = [parent convertPoint:parent.center fromView:parent.superview];

And for Swift:

child.center = parent.convert(parent.center, from:parent.superview)