swiftuinavigationbarsubviewlayoutsubviews

place NavigationBar subview behind the NavigationBarItem and title


I want to add a view below everything that's on the navigationBar. I need to add them as subviews to my NavigationBar so that they appear on any detail ViewController.

Here is what I tried so far inside my custom NavigationBar subclass (I call this method inside layoutSubviews()):

private var backgroundView = UIView()

backgroundView.frame = CGRect(x: 0, y: 0, width: 100, height: 70)
backgroundView.backgroundColor = .blue
backgroundView.alpha = 0.7
self.insertSubview(backgroundView, at: 0)

And this is what I get:

navigationBar with subview

The backgroundView appears on top of the title and the NavigationBarItem.

What can I do?


Solution

  • According to this post on the apple developer forum, you can do this inside the NavigationBar class (which works!):

    self.subviews[0].insertSubview(backgroundView, at: 0)