Programmatically Centering UIViews
- by David Foster
I've seen a bunch of similar questions to this, but nothing seems to be completely what I'm looking for. Do forgive me if I have missed the solution answered in another question, though!
Right. I have a view. 160 pixels both tall and wide. I know that this view is going to be used as a subview, and I know that it always needs to be centered about both axis in whatever situation it's used.
If defining the view programmatically, how can I be sure that it is always perfectly centered, horizontally and vertically, relative to its superview?
So far, all I have is this simple code:
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:CGRectMake(80, 150, 160, 160)];
self.view.backgroundColor = [UIColor greenColor];
self.view.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
[self.view release];
}
This does the centralization, but only in the simplest of cases. Any insight is greatly appreciated.