Constraints can be assigned to UINavigationBar that is added manually to the view.
But when the UINavigationBar is added to a view when and the view is embedded in a Navigation Controller, I am not able to add constraints to the same.
My objective is to increase the height of the UINavigationBar
UINavigationBar does not allow to assign constraints to itself. The only easy way that the height can be changed is by adding a space to the prompt property.
To increase the the height of the UINavigationBar there are two steps:
- Sub-class the UINavigationBar class and overriding the method that give the height to the UINavigationBar, this class thereafter needs to be assigned to the NavBar of the Navigation Controller
Note: All the views under that particular Navigation Controller will have the new height
Code Snippet:
class ModifiedNavBar: UINavigationBar {
override func sizeThatFits(size: CGSize) -> CGSize {
let screenWidth = UIScreen.mainScreen().bounds.width
let newSize:CGSize = CGSizeMake(screenWidth, 60)
return newSize
}
}
Note: The above step increases the height of the NavBar but it does not give you full customisation options. Adding a view gives you full control over the same.
- Create a view programmatically and then adding it to the UINavigationItem (titleView) Outlet:
Code Snippet:
class ViewController: UIViewController {
/*** UINavigationItem Outlet ***/
@IBOutlet weak var navbar: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
let view = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 90))
let label = UILabel(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 20))
let label2 = UILabel(frame: CGRectMake(0, 20, UIScreen.mainScreen().bounds.width, 20))
/*** First Label ***/
label.text = "Hello"
label.textAlignment = NSTextAlignment.Left
view.addSubview(label)
/***Second Label ***/
label2.text = "Hello2"
label2.textAlignment = NSTextAlignment.Left
view.addSubview(label2)
self.navbar.titleView = view
}
Note: If prompt is added to any of the UINavigationItem objects the size of the NavBar will increase