2

I'm doing everything programmatically, and have no Storyboards. I'm using Swift2.0 and I'm a beginner. My app structure is very simple:

In my AppDelegate, I am initializing a UINavigationController and a ViewController, and adding my ViewController to my navigationController.

In my ViewController, loadView() method, I initialize my view: self.view = myView()

And so now I'm in myView class, where I'm trying to build my view (making 4 buttons, adding constraints). Now when I want to make my buttons, I need to know the navigationController's navigationBar size (height).

How can I access this from my View class? What is the best way to do this?

Thank you.

Krunal
  • 77,632
  • 48
  • 245
  • 261
0b10110
  • 29
  • 1
  • 5
  • 1
    "And so now I am in myView class" Where exactly? What method are you in? This makes a huge difference as to what you can do. – matt Feb 24 '16 at 19:04
  • 1
    Possible duplicate of [Programmatically get height of navigation bar](http://stackoverflow.com/questions/7312059/programmatically-get-height-of-navigation-bar) – DeyaEldeen Feb 24 '16 at 20:11
  • Right now, in my init method, I am calling a method that does all the layout for the view (adds all the buttons and constraints) – 0b10110 Feb 25 '16 at 18:16

1 Answers1

0

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

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)
Krunal
  • 77,632
  • 48
  • 245
  • 261