How do I add a UINavigationBar completely programmatically?

74 views Asked by At

I'm trying to figure out, given a UIViewController subclass, how to add a UINavigationBar to it. All the questions and answers seem to be either embed it in a navigation controller (not possible in this case) or via Storyboard, but I need to do it completely in code.

Do I just add it as a subview of the view controller's view? Will it become topLayoutGuide after I pin it to the topLayoutGuide, which would be the status bar prior to adding it? Or am I supposed to be setting an attribute on the view controller I cannot figure out, instead of adding it?

1

There are 1 answers

0
DBoyer On

Your on the right track, you just add as a subview like you would any other view. The trick to the status bar is setting yourself as the navigationBar delegate and returning UIBarPositioningTopAttached in the delegate method

.....

self.customNavigationBar.delegate = self;
[self.addSubview self.navigationBar]; 

....

- (UIBarPosition)positionForBar:(id<UIBarPositioning>)bar {
    return UIBarPositioningTopAttached;
}