Question

I have some custom buttons I add to the view in -viewDidLoad. I want them centered vertically inside the view, like so:

self.customButton.center = CGPointMake(98.f, self.view.center.y);

However, the view height is 504.0 even on a 3.5" device, where I expect it to be 416 (480 - 20 (status bar height) - 44 (nav bar height)).

The view in xib is using "Retina 4 Fullscreen", but setting it to freeform does not help. I certainly don't want two xibs just to account for the height difference.

I know I can use UIScreen but I would prefer that the view be aware of the height difference.

EDIT: the odd thing is, in -viewWillAppear, view height is correctly set to 416.0. Why this isn't handled after [super viewDidLoad] is beyond me.

How are people handling this? Autolayout would probably handle this but I need a iOS5 compatible method. Can autoresizing handle "centering" somehow?

Was it helpful?

Solution

You don't have Autolayout in iOS5, but you do still have the autoresizing mask. If you center a view vertically in IB, go to the inspector and deselect the vertical struts and springs in the autolayout masks, the view will stay centered vertically on both 4" and 3.5" screens.

Or you can do this in code in your viewDidLoad method. Just center the view as you are now and set the autoresizingMask like this:

 self.customButton.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin | \
                                       UIViewAutoresizingFlexibleTopMargin);

OTHER TIPS

EDIT: the odd thing is, in -viewWillAppear, view height is correctly set to 416.0. Why this isn't handled after [super viewDidLoad] is beyond me.

Because resizing the view is not part of loading the view! -viewDidLoad gets called from -view in a method that probably looks a bit like this:

-(UIView*)view
{
  if (!_view)
  {
    [self loadView];
    [self viewDidLoad];
  }
  return _view;
}

-(void)loadView
{
  // Some code to load the view from a nib/storyboard...
}

The view will get resized with a call like yourViewController.view.frame = ..., but this can only happen after the view is loaded (and thus after -viewDidLoad is called).

Set some autoresizing masks. That's what they're there for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top