I have two ViewControllers. I want to add an UIView over the navigation bar.
I could add the UIView on top of the first navigation bar by creating an UINavigationItem Outlet and adding the UIView created programatically to the UINavigationItem outlet titleView.
Code Snippet (HomeVC - Fist ViewController):
class HomeVC: UIViewController {
@IBOutlet weak var homeNavigationItem: UINavigationItem!
let navBarView = UIView()
let topNavBarLabel = UILabel()
let screenWidth = UIScreen.main.bounds.width
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navBarView.frame = CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 50.0)
topNavBarLabel.text = "Hello World"
topNavBarLabel.textAlignment = NSTextAlignment.center
topNavBarLabel.textColor = UIColor.white
topNavBarLabel.frame = CGRect(x: 0.0, y: 10.0, width: screenWidth, height: 20.0)
navBarView.addSubview(topNavBarLabel)
homeNavigationItem.titleView = navBarView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Screenshot Home View:
Now incase of the SecondVC I am trying to do the same thing after the Push Segue.
Code Snippet (DetailVC - Second ViewController):
class DetailsVC: UIViewController {
let navBarView = UIView()
let screenWidth = UIScreen.main.bounds.width
let navBarTopLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navBarView.frame = CGRect(x: 0.0, y: 50.0, width: screenWidth, height: 50.0)
navBarView.backgroundColor = UIColor.black
navBarTopLabel.frame = CGRect(x: 0.0, y: 10.0, width: screenWidth, height: 20.0)
navBarTopLabel.textColor = UIColor.white
navBarTopLabel.text = "Details Hello"
navBarTopLabel.textAlignment = NSTextAlignment.center
navBarView.addSubview(navBarTopLabel)
self.view.addSubview(navBarView)
self.view.bringSubview(toFront: navBarView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Screenshot Details View:
Storyboard Screenshot:
View Hierarchy:
Note: I deliberately assigned an Y-position to the view more than 0, to be sure that the view is being created
But as I am not able to create an UINavigationItem, I am adding the programmatically created view to the view and even trying to bring the subView to the front.
Note: Yes, the size of the UINavigationBar has been increased, please refer here: Change width/height UINavigationBar embedded in a Navigation Controller