There is a way to use the NavigationItem
in interface builder for this.
First add a NavigationItem
to your ViewController
in the interface builder, like you would with a NavigationController
. Make sure to make the NavigationBar
is visible by selecting something other than Inferred
and None
under simulated metrics.
Second, in viewDidLoad
, just add the following lines:
- (void)viewDidLoad
{
[super viewDidLoad];
UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame: frame];
bar.items = @[self.navigationItem];
[self.view addSubview: bar];
}
As for frame
, width
will be the same as your ViewController
and height
will be either 44.0
or 64.0
depending if the status bar
is visible or not.
CGFloat navigationBarHeight = 44.f + [UIApplication sharedApplication].statusBarFrame.size.height;
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, navigationBarHeight);
And if you wish to support different orientations use NSLayoutConstraints
:
CGFloat navigationBarHeight = 44.f + [UIApplication sharedApplication].statusBarFrame.size.height;
[self.view addConstraints: @[
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeLeft
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeLeft
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeRight
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeRight
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeTop
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeTop
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: bar
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 1.0
constant: navigationBarHeight],
]];