Create NavBar programmatically with Button and Title Swift
Basically azimov's answer in Swift 4
override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationBar()
}
func setNavigationBar() {
let screenSize: CGRect = UIScreen.main.bounds
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 44))
let navItem = UINavigationItem(title: "")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: nil, action: #selector(done))
navItem.rightBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
self.view.addSubview(navBar)
}
@objc func done() { // remove @objc for Swift 3
}
Updated for Swift 5
Create a navigation item instance and set title and right/left buttons to it. After navigation item is configured add it to the navigation bar.
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 44))
view.addSubview(navBar)
let navItem = UINavigationItem(title: "SomeTitle")
let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(selectorName:))
navItem.rightBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)