modal UINavigationController bar with wrong height

Viewed 590

NOTE: This is not about the new default modal presentation style used in iOS 13.

I have a strange issue presenting a modal UINavigationController.

Consider an UIViewController that is inside an UINavigationController:

enter image description here

When this code runs on iOS 13.0 :

@IBAction func btntap(_ sender: Any) {

    let errorViewController = UIViewController()
    errorViewController.view.backgroundColor = .blue
    errorViewController.title = "Erro na solicitação"

    let errorNavigation = UINavigationController()

    errorNavigation.navigationBar.barTintColor = UIColor(red: 204/255, green: 0/255, blue: 0/255, alpha: 1.0)

    errorNavigation.navigationBar.tintColor = UIColor.white
    errorNavigation.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]

    errorNavigation.setViewControllers([errorViewController], animated: false)

    errorNavigation.modalPresentationStyle = .automatic

    self.present(errorNavigation, animated: true, completion: nil)
 }

This happens:

enter image description here

Note the wrong height when we present the modal screen on the first time:

enter image description here

I want to continue using the card-like presentation, but I need to fix this wrong height issue on the first present.

This happens when the following requirements are met:

  1. The presenting UIViewController is inside an UINavigationController

  2. The presented UIViewController has special chars on its title ("ç", "ã", etc)

  3. The present is animated true

Already tried some variations of layoutIfNeeded() but none worked.

How can I present this with the right height on the first present?

1 Answers

just replace the viewcontroller's title with your own label like so. this is a hack solution but will always work and you'll never have to think about it again. in fact, i never invoke the title property of viewcontrollers, i only use labels and set them as the titleView so i can control number of lines, subtitles, justification, etc.

    let errorViewController = UIViewController()
    errorViewController.view.backgroundColor = .blue

    let errorNavigation = UINavigationController()
    let label = UILabel()
    label.text = "Erro na solicitação"
    label.textColor = .white

    errorViewController.navigationItem.titleView = label

    errorNavigation.navigationBar.barTintColor = UIColor(red: 204/255, green: 0/255, blue: 0/255, alpha: 1.0)

    errorNavigation.navigationBar.tintColor = UIColor.white

    errorNavigation.setViewControllers([errorViewController], animated: false)

    errorNavigation.modalPresentationStyle = .automatic

    self.present(errorNavigation, animated: true, completion: nil)

oh yes, and on that note, the font size should be around 17-18 from medium to bold to match ios default system for title value for viewController should you wish to match the ios system defaults

Related