Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding Navigation Bar programmatically iOS using Swift
To add navigation bar programmatically we’ll go through a series of steps that are mentioned below. We’ll be doing this in ViewWillLayoutSubviews method of our viewController.
Getting the width of the current View.
let width = self.view.frame.width
Creating a navigation bar with the width of our current view and height of 44 px which is the default height of a navigation bar.
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
Adding the newly created navigation bar to our view.
self.view.addSubview(navigationBar)
We can further extend this example to add a title and a button to our View. The complete result should look something like the class below.
class ViewController: UIViewController {
override func viewWillLayoutSubviews() {
let width = self.view.frame.width
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
self.view.addSubview(navigationBar);
let navigationItem = UINavigationItem(title: "Navigation bar")
let doneBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector(selectorX))
navigationItem.rightBarButtonItem = doneBtn
navigationBar.setItems([navigationItem], animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
}
@objc func selectorX() { }
}
When we execute this example our result should look like.

Advertisements