Tiois
Tiois

Reputation: 1559

Add a subview as a background to a Navigation Bar

I'm using a Navigation Controller in my application and I'm trying to make a progress bar as the background of my Navigation Bar. I made a subclass of UIView to make my progress bar, this works fine.

Now when I build my Navigation Bar Items, I add my progress bar as a SubView of my navigation bar, as well as 2 buttons. This works fine too!

The problem is when I click in a row of my tableview, this makes a segue to a View Controller, and when I click the "Back" button, my progress bar in now on top of the buttons in my Navigation Bar.

Here's the code where I setup the navigation bar items :

    let progressBar = ScrollProgress(frame: CGRect(x: 0, y: -20, width: self.navigationController!.navigationBar.frame.width, height: self.navigationController!.navigationBar.frame.height + 20), section: nil)
    progressBar.tag = 10
    progressBar.pourcentage = 92

    self.navigationController!.navigationBar.addSubview(progressBar)

    let menuButton = UIBarButtonItem(title: "Menu", style: UIBarButtonItemStyle.Plain, target: revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)))
    self.navigationItem.leftBarButtonItem = menuButton

    let favorisButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Bookmarks, target: revealViewController(), action: #selector(SWRevealViewController.rightRevealToggle(_:)))
    self.navigationItem.rightBarButtonItem = favorisButton

    self.navigationItem.title = "Demo App"

You can see here that it works fine, the progress bar covers 92% of the width of my navigation bar, and is UNDER the buttons and title :

enter image description here

Then when I click on a row of my tableview, this performs the segue to another ViewController, it works fine :

enter image description here

When I click the back button (Retour), my progress bar appears on top...

enter image description here

I can't find out why the subviews order is changing. I tried to replace my subview to the correct index with self.navigationController!.navigationBar.exchangeSubviewAtIndex, it works but the title is flickering at the end of the transition (but the buttons are not flickering).

Is there another way to do this, or am I doing something wrong?

Any help would be appreciated!

Upvotes: 4

Views: 2469

Answers (1)

konnn
konnn

Reputation: 11

You can try not just to add a progress bar, but to insert it into the very bottom of the navigation bar insertSubview(view: UIView, at: Int). This worked for me.

self.navigationController!.navigationBar.insertSubview(progressBar, at: 0)

Upvotes: 1

Related Questions