Search code examples
nslayoutconstraintawakefromnib

View of frame not appeared to have set in awakeFromNib


I am using autolayout in my view controller, to align a uiview as if it were a navigation bar (aligned to top, stretched to trailing and leading sides and 44 height).

I have subclassed this view, and during awakeFromNib I want to add subviews to it.

However, when I adding these subviews (also with constraints to the parent view) it doesn't work.

Initially I thought the constraints were programmed incorrectly, however, after logging the frame of the view like so:

- (void)awakeFromNib
{
    [super awakeFromNib];

    NSLog(@"%@", NSStringFromCGRect(self.frame));
}

I get the following output:

2012-11-27 03:25:25.976 myApp[8262:c07] {{0, 0}, {0, 0}}

Yet when I log in, for example, touchesBegan:withEvent: it logs the correct frame size.

Does anyone know what might be causing this?

I have also tried setting setTranslatesAutoresizingMaskIntoConstraints:NO on all views involved. But nothing seems to work.

Thanks in advance!


Solution

  • When awakeFromNib is called, the view is not yet created. The best way to get properties of any kind from the view in this method is to call [self view] before trying to access properties.