Get frame height without navigation bar height and tab bar height in deeper view hierarchy
Solution 1
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
Solution 2
For UITabBar, this code work :
self.tabBarController?.tabBar.frame.height
Solution 3
For Swift 3
navBarHeight = (self.navigationController?.navigationBar.intrinsicContentSize.height)!
+ UIApplication.shared.statusBarFrame.height
Solution 4
As for iOS 13, since the statusBarFrame
property of a UIApplication object was deprecated, one can use:
let statusBarHeight = navigationController?.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0
Now, it may seem that doesn't help you @OP since your navigationController is nil, but you could try to use view.window?.windowScene?.statusBarManager?.statusBarFrame.height
for the statusBar height and figure out a way to find the navBar height as well? Hope that helps :)
Solution 5
iOS 13 solution:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
return (window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
To call it you can just use: self.topbarHeight
in viewController
Darko D.
Updated on July 09, 2022Comments
-
Darko D. almost 2 years
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)