Search code examples
iosswiftuiviewcontrolleruinavigationcontroller

How to create a UINavigationControll in UIViewController programmatically Swift


I´m creating a multiScene app for iOS in Swift Storyboard. I want to add a UINavigationController programmatically in UIViewController or if there is possible with storyboard, I have made a lot a research for this and I haven´t find anything valuable.

In each view controller I want to add the Navigation Controller

Also I have create one but is not responsible for all phones and the button does not work

override func viewDidLoad() {
    super.viewDidLoad()
    let height: CGFloat = 50
    let width = self.view.frame.width
    let navbar = UINavigationBar(frame: CGRect(x: 0, y: 40, width: width, height: height))
    navbar.backgroundColor = UIColor.white
    navbar.delegate = self

    let navItem = UINavigationItem()
    navItem.title = "Last Call"
    navItem.rightBarButtonItem = UIBarButtonItem(title: "Add New", style: .plain, target: self, action: nil)

    navbar.items = [navItem]

    view.addSubview(navbar)

    self.view.frame = CGRect(x: 0, y: height, width: width, height: (UIScreen.main.bounds.height - height))

}

I have embed a Navigation controller in my view controller and this is how it looks like This is how it looks like


Solution

  • Maybe have a look at "Showing and Hiding View Controllers" where some navigation concepts are explained: https://developer.apple.com/documentation/uikit/view_controllers/showing_and_hiding_view_controllers

    When using storyboards you should be able to use a segue to navigate from one view controller to another.