Take the 2-minute tour ×

I created a UIView xib in Interface Builder and tried everything I could to indicate that the UIView should center itself, anchor itself at center, orient itself in central coordinates, etc. etc.

But whenever I add it as a subview in code, I also have to programmatically set its frame up with CGRectMake() or else it will always add to the top-left of its parent. The math to reframe it is pointless and ugly, so I presume I'm just not twiddling a bit in the IB inspector correctly.

Can anyone confirm this is possible, and if so, what I need to do in IB to accomplish this?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

Centering but maintaining size isn't possible in IB. Centering but maintaining margins to its superview is though.

You will have to override the layoutSubviews message or simply keep the calculation code you wrote.

share|improve this answer
Justin Searls: The fault isn't IB's. Your problem is that the autoresizingMask only applies to resizing the view's superview; the mask defines what effect this has on the view. If there is no superview yet, then there is no “centered”, because “centered” refers to the view's placement within its superview. You can't keep the view centered, which is what the autoresizing mask does, until the view has a superview for it to be centered in. So, when you put the view into a superview yourself, you need to adjust its frame yourself. –  Peter Hosey Feb 8 '10 at 2:21
@JustinSearls The Windows Forms and WPF GUI classes present auto resizing in pretty much the same capacity. –  Nick Bedford Feb 8 '10 at 3:40

Why don't you just set .center of the subview just added, to be the point created by halving the width and height of the superview?

Either that or define the rectangle that view is going into with IB (I'm imagining a container view) and simply set the frame of the view you are adding to containerView.bounds (bounds is a position independent value and so x,y will be 0 while size will equal the container size.

share|improve this answer
Even easier than halving the width and height yourself: CGRectGetMidX and CGRectGetMidY. developer.apple.com/mac/library/documentation/GraphicsImaging/… –  Peter Hosey Feb 8 '10 at 6:23
While technically true, it's actually less typing to say self.bounds.width/2 than CGRectGetMidX( self.bounds )! Possibly the Apple function does something slightly more clever though. –  Kendall Helmstetter Gelner Feb 8 '10 at 20:28

Your Answer


