Question

I'm attempting to use a UINavigationController that utilizes a custom subclass of UINavigationBar. However, I'm running into a problem with initWithFrame. When initWithFrame is called, I print out the dimensions and it shows a 0.0 width and 0.0 height. But, when I print out the same frame in -(void) layoutSubviews inside of the UINavigationBar subclass, the frame is correctly set. Why is initWithFrame receiving a zero-sized frame, and what can I do to fix this? It doesn't sound correct to be manually calling initWithFrame or anything like that, since UINavigationController should take care of that. Here is the relevant code:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class] toolbarClass:nil];
    CoolViewController *vc = [[CoolViewController alloc] init];
    [navController pushViewController:vc animated:YES];
    self.window.rootViewController = navController;

    [self.window makeKeyAndVisible];

    return YES;
}

CustomNavigationBar.m

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        NSLog(@"initWithFrame with frame: %f, %f", frame.size.width, frame.size.height); // This prints "initWithFrame with frame: 0, 0"
    }

    return self;
}

Thank you!

Was it helpful?

Solution

I believe the navigation controller doesn't actually set the frame size to a specified value. Instead, it asks the navigation bar for its sizeThatFits: and uses that. By definition, that can't be done and passed to initWithFrame:. So, you want to use a combination of sizeThatFits:, setFrame: and layoutSubviews to add, size and reset your navigation bar content.

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