Search code examples
iosuinavigationcontrolleruinavigationbarswift4

Custom Navigation Bar With Background


As i'm new to Swift and working on my FYP, I have a multiple VC's and now i'm going to reach on below attached VC by .pushViewController(nextVC, animated: true). I am trying to make Nav Bar transparent so that background image will be show behind the Nav Bar:

image

And currently my Nav Bar looks like:

image

here is my code,

override func viewDidLoad() {
    super.viewDidLoad()

    //------
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
}

Hope so you guys understand my Question. Any help will be highly appreciated. Thanks


Solution

  • After a long struggle i got my problem solution. You can say it's tricky but Might be help for you with Xcode 9 and later and swift 4.

    As concerning to my Question, i'm coming to this VC by pushViewController(), so when i reach on that VC, simply i'm using here ViewWillAppear() to change my NavBar and after moving back from this VC to previous VC or any other controller so that i need to reset original Navigation to back it's original style, for that purpose i'm using viewWillDisappear().

    Step 1:

    override func viewWillAppear(_ animated: Bool) {
    
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.isTranslucent = true
    
    }
    override func viewWillDisappear(_ animated: Bool) {
    
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.shadowImage = nil
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.isTranslucent = true
    
    }
    

    Step 2:

    For increase Navigation Bar height, i have added white spaces in prompt of Navigation Item and also set y-coordinate to -20 to reach NavBar to top of status bar under navigation bar from Storyboard.

    Step 3: last and final is

    I have set my Alpha value under Navigation Bar from storyboard is 0.5

    And that's all for me, and works for me very nicely. Also you can see my output after above all steps.

    enter image description here