Programmatically get height of navigation bar

前端 未结 14 1156
猫巷女王i
猫巷女王i 2020-12-04 08:02

I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height. I also know that this height = 44px. I have also discovered tha

14条回答
  •  没有蜡笔的小新
    2020-12-04 08:46

    With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).

    Try this if you want exact height of top bar (both navigation bar + status bar):

    UPDATE

    iOS 13

    As the statusBarFrame was deprecated in iOS13 you can use this:

    extension UIViewController {
    
        /**
         *  Height of status bar + navigation bar (if navigation bar exist)
         */
    
        var topbarHeight: CGFloat {
            return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
                (self.navigationController?.navigationBar.frame.height ?? 0.0)
        }
    }
    

    Objective-C

    CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
           (self.navigationController.navigationBar.frame.size.height ?: 0.0));
    

    Swift 4

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

    For ease, try this UIViewController extension

    extension UIViewController {
    
        /**
         *  Height of status bar + navigation bar (if navigation bar exist)
         */
    
        var topbarHeight: CGFloat {
            return UIApplication.shared.statusBarFrame.size.height +
                (self.navigationController?.navigationBar.frame.height ?? 0.0)
        }
    }
    

    Swift 3

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

提交回复
热议问题