3

I want to subclass UINavigationBar so that I can do custom drawing in its drawRect:.

Here's my code:

Navigation Controller (.h)

@interface CORENavigationController : UINavigationController

@property (strong, nonatomic) CORENavigationBar *customNavigationBar;

@end

Navigation Controller (.m)

@implementation CORENavigationController

@synthesize customNavigationBar = _customNavigationBar;

- (UINavigationBar *)navigationBar {
    if (![self customNavigationBar]) {
        [self setCustomNavigationBar:[[CORENavigationBar alloc] init]];
    }
    return [self customNavigationBar];
}

Navigation Bar (.h)

@interface CORENavigationBar : UINavigationBar

@end

Navigation Bar (.m)

@implementation CORENavigationBar

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
}

The issue is that the navigation bar has no title, e.g. all I can see is just the standard blue background.

As soon as I remove the following method, the title is back there:

- (UINavigationBar *)navigationBar {
    if (![self customNavigationBar]) {
        [self setCustomNavigationBar:[[CORENavigationBar alloc] init]];
    }
    return [self customNavigationBar];
}

Why does the title disappear? I call the super's drawRect: and do not change anything else.

Thanks!

Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
  • question is unclear. "As soon as I remove this method" being which method? drawRect or the one after the colon? If it's `drawRect` then it's a very interesting question ;) – Dan Rosenstark May 25 '12 at 23:24
  • @Yar Fixed. It's the method that follows after the colon. Simply put, as soon as I don't override `navigationBar`, the title is back there. Hopefully it's clearer. Thanks for comment! – Rudolf Adamkovič May 25 '12 at 23:38
  • It's possible that the `navigationBar` method returns a concrete subclass of `UINavigationBar` or at the very least sets up the instance. Debug and see. – Dan Rosenstark May 26 '12 at 00:53
  • possible duplicate of [Set a custom subclass of UINavigationBar in UINavigationController programmatically](http://stackoverflow.com/questions/1869331/set-a-custom-subclass-of-uinavigationbar-in-uinavigationcontroller-programmatica) – Dan Rosenstark May 26 '12 at 13:54

1 Answers1

3

Found it! Here's the answer:

https://stackoverflow.com/a/9610801/1306956

In this case, it'd be:

[navigationController setValue:[[CORENavigationBar alloc] init] forKeyPath:@"navigationBar"];

Tested on iOS 5.1.1 (9B206). Works like a charm.

Community
  • 1
  • 1
Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118