uranusjr
uranusjr

Reputation: 1459

How do I make views pushed into a UINavigationViewController resize properly?

I’m trying to create a view controller hierarchy programmatically (without IB and Storyboard). Things work well if I use a plain UIViewController:

// My app delegate
func application(application: UIApplication, didFinishLaunchingWithOptions options: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let vc = UIViewController(nibName: nil, bundle: nil)
    vc.view = UIView(frame: CGRectZero)
    vc.view.backgroundColor = UIColor.whiteColor()
    let label = UILabel(frame: CGRectMake(0, 0, 100, 40))
    label.text = "Hello!"
    vc.view.addSubview(label)
    vc.title = "Title"

    self.window.rootViewController = vc
    self.window.makeKeyAndVisible()
    return true
}

Then I try to put the view controller inside a navigation controller:

func application(application: UIApplication, didFinishLaunchingWithOptions options: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    // vc created the same way as above.

    let nav = UINavigationController(rootViewController: vc)
    self.window.rootViewController = nav

    self.window.makeKeyAndVisible()
    return true
}

And the label is hidden under the navigation bar.

So obviously the view isn’t resized properly by the navigation view controller. I tried setting the frame of the inner vc, but that does not have an effect, probably because things are handled by autolayout instead? Should I add some constraints to make this work properly like in IB/Storyboard, or should I do some things differently?

Upvotes: 0

Views: 80

Answers (1)

mttcrsp
mttcrsp

Reputation: 1651

Your view is being resized correctly but in iOS 8, since bars can be translucent, views extend under them by default. (That's the reason why your label is hidden by the navigation bar)

From what I'm understand you want to use a translucent bar but you don't want your content to end up under them. To accomplish this you can edit the edgesForExtendedLayout property of your view controller.

vc.edgesForExtendedLayout = UIRectEdgeNone

This property tells you what edges should be extended under translucent bars (left, right, top, bottom, all, none or any combination of those) and defaults to UIRectEdgeAll.

For more informations check out the documentation and this guide.

Upvotes: 1

Related Questions