views:

539

answers:

2

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?

A: 

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.

Nick Bedford
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
@JustinSearls The Windows Forms and WPF GUI classes present auto resizing in pretty much the same capacity.
Nick Bedford
+1  A: 

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.

Kendall Helmstetter Gelner
Even easier than halving the width and height yourself: `CGRectGetMidX` and `CGRectGetMidY`. http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectGetMidX
Peter Hosey
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