Search code examples
iosresizeios6uinavigationbarsubclassing

Custom UINavigationBar sizeThatFits implementation not returning real frame.size.width


I am trying to subclass UINavigationBar with a defined height and trying to implement sizeThatFits method:

@implementation NavigationBar

- (CGSize)sizeThatFits:(CGSize)size {
    NSLog(@"frame: %@", NSStringFromCGRect(self.frame));
    return CGSizeMake(self.frame.size.width, 62);
}

@end

But apparently the self.frame.size.width is always returning a weird value which isn't 1024 which is what I am aiming for and it is causing the behaviour presented below:

NSLog output:

> frame: {{224, 20}, {576, 62}}

While manually defining CGSizeMake(1024, 62) this will cause the following:

hiding the buttons and the NSLog output will be:

> frame: {{-128, 20}, {1280, 62}}

Any idea on how to properly implement this method so the navigation bar extends across all window?


Solution

  • using layoutSubviews and sizeThatFits together seems to work:

    - (CGSize)sizeThatFits:(CGSize)size {
        return CGSizeMake(1024, 62);
    }
    
    - (void)layoutSubviews {
        [super layoutSubviews];
        self.frame = CGRectMake(0, 20, 1024, 64);
    }