Programmatically Centering UIViews

Posted by David Foster on Stack Overflow See other posts from Stack Overflow or by David Foster
Published on 2010-03-26T16:33:30Z Indexed on 2010/03/26 16:53 UTC
Read the original article Hit count: 414

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about gui