2

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?

2 Answers 2

9

If you want to avoid using "magic numbers", use could try to use UINavigationBar superview's size.

- (CGSize)sizeThatFits:(CGSize)size
{
    return CGSizeMake(self.superview.bounds.size.width, 62.0f);
}

Works well for me on iOS 6. No need to override layoutSubviews.

3
  • What needs to be added for this to work when orientation changes?
    – Randy Hunt
    Apr 26, 2013 at 12:15
  • @RandyHunt It seems nothing is required. iOS queries for this size on rotations automatically. Apr 26, 2013 at 12:42
  • Thus, call [super sizeThatFits:size]; return self.superview.bounds.size; ?!
    – Yoon Lee
    Jan 31, 2015 at 9:29
0

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);
}
2
  • Hi Liam, I have tried that before. layoutSubview won't take the navigationBar height into account and it will simply overlay the content below the bar instead of applying the correct space.
    – zanona
    Dec 5, 2012 at 11:29
  • thanks Liam, I think I found something that may have worked, but only because of your initial help :), if you are happy with it you can edit your answer and I will mark it as correct. What I have done was this (pastebin.com/X5svpW7s). So I had to implement both methods. cheers
    – zanona
    Dec 5, 2012 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.