0

I'm trying to learn how to programmatically create the UI of my application. I added to the application a navigation controller with code, this is the code:

AppDelegate:

    var window: UIWindow?
var navigationController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    if let window = window{
        let mainVC = MainVC()
        navigationController = UINavigationController(rootViewController: mainVC)
        window.rootViewController = navigationController

        window.makeKeyAndVisible()
    }
    return true
}

And this is my mainVC:

    class MainVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white

        navigationController?.navigationBar.isTranslucent = false

        navigationController?.navigationBar.barTintColor = UIColor.blue
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Hello"
        setupTextBox()
        // Do any additional setup after loading the view, typically from a nib.
    }

    let textBox: UITextField = {
        var tBox = UITextField(frame: CGRect(x: 100, y: 100, width: 200, height: 30))
        tBox.placeholder = "Please Enter Name"
        tBox.textAlignment = .center
        tBox.borderStyle = .roundedRect
        tBox.backgroundColor = UIColor.red

        return tBox
    }()

    private func setupTextBox(){
        view.addSubview(textBox)
    }
}

The navigation bar does appear but it is huge, couldn't find a way to view it as it should be. This is the image of the navigation bar:

enter image description here

What am I doing wrong?

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
John Doah
  • 1,839
  • 7
  • 25
  • 46

3 Answers3

3

Its because of navigationController?.navigationBar.prefersLargeTitles = true You are doing well Just must to understand that it is iPhone X with top safe area + LARGE TITLE

Yura
  • 262
  • 2
  • 11
1

You're not doing anything wrong. That's simply how a UINavigationBar looks on iPhone X, iPhone XR and iPhone XS. All of these devices have the "X" bevel.

Here's another helpful SO post: What is the top bar height of iPhone X?

Jacob M. Barnard
  • 1,347
  • 1
  • 10
  • 24
1

The large navigation bar is a style of navigation bar that is used when prefersLargeTitles is set. So this line is causing your issue

navigationController?.navigationBar.prefersLargeTitles = true

Change that to false and you should get a smaller* navigation bar

Note: * it will still be larger than normal due to the 'notch' on the iPhone X range of devices

Scriptable
  • 19,402
  • 5
  • 56
  • 72