Augusto Carmo
Augusto Carmo

Reputation: 4964

Get the default height (or maxY) of a NavigationBar on iOS

I would like to know if is there any way for us to obtain the default Navigation Bar height (maxY preferably) of a NavigationController.

Knowing that iOS 11 introduced large titles, is there any way for us then to get the default height (or maxY) of a Navigation Bar with a "small title" and of a Navigation Bar with a "large title"?

The reason I am asking this is because I am making the Navigation Bar's background transparent and introducing my own background to it (which is an Effect View). But the problem I am having is that every time I run the following code

self.navigationController?.navigationBar.frame.maxY

it returns a number ways higher than the expected :/

I tried to run this piece of code on many callbacks -> onViewWillAppear, onViewDidAppear, onViewDidLoad

Upvotes: 0

Views: 4624

Answers (4)

Stephen Liu
Stephen Liu

Reputation: 141

The best approach I found so far, without having to create a navigation controller instance:

[self.navigationBar sizeThatFits:CGSizeZero].height;

And just to mention, it supports screen orientation change too.

Upvotes: 1

Aanchal Chaurasia
Aanchal Chaurasia

Reputation: 629

I have used the native method to get the height of navigation bar including status bar. Use this line of code to get the navigation bar height and use as per your requirement. This worked for me perfectly fine on all devices & different iOS versions.

let navigationBarHeight = UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)

Upvotes: 3

RajeshKumar R
RajeshKumar R

Reputation: 15758

You can get the height of navigation bar and status bar using this

  override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let topSpace:CGFloat?
        if #available(iOS 11.0, *) {
            topSpace = self.view.safeAreaInsets.top
        } else {
            topSpace = self.topLayoutGuide.length
        }
        print(topSpace)
  }

Upvotes: 6

PontusJ
PontusJ

Reputation: 514

This works for me

let navigationBarHeight = UIApplication.shared.statusBarFrame.size.height +
    (self.navigationController?.navigationBar.frame.height ?? 0.0)

Even tough your method may be the best solution for you I mostly try to not use the native navigation bar but hide it and create my own instead. This makes it easier to use custom and more advanced designs in the application.

Upvotes: 0

Related Questions