Get frame height without navigation bar height and tab bar height in deeper view hierarchy

Darko D. picture Darko D. · May 28, 2015 · Viewed 35.2k times · Source

I have a ViewController (B) which is handled by a PageViewController which is inside another ViewController (A) and open it modal. I have centered the ViewController (B) exactly in the middle of the screen. This works fine.

But when I push the ViewController (A) from a NavigationController the frame of ViewController (B) is to big and extends below the NavigationBar and the TabBar. But I want it centered between the NavigationBar and the TabBar.

I know how I can get the height of the navbar and the tabbar so I could resize ViewController (B):

var topBar = self.navigationController?.navigationBar.frame.height
var bottomBar = self.tabBarController?.tabBar.frame.height

But this does not work deep down in the vier hierarchy in ViewController (B). self.navigationController and self.tabBarController are nil. So how can I get the height of the navbar and tabbar deeper down in the view hierarchy? Or do I just have to pass it down from one ViewController to another till I reach ViewController (B)? Or is there another more obvious way to center the view? Thanks.

(I have tried to post screenshots for better understanding but I miss the needed reputation points to post images, sorry)

Answer

Ehsan Jelodar picture Ehsan Jelodar · Mar 18, 2016

Use this :

let height = UIApplication.sharedApplication().statusBarFrame.height +
self.navigationController!.navigationBar.frame.height

this support portrait and landscape state.

Swift 5

let height = UIApplication.shared.statusBarFrame.height +
      self.navigationController!.navigationBar.frame.height