taufan
taufan

Reputation: 219

Set Image Underlay of Transparent Navigation Bar and Status Bar in Swift iOS 8

I am new in iOS swift development and I am facing a problem. I want to set transparent navigation bar and make image underlay of transparent navigation bar and status bar like image below,

enter image description here

But after I implemented the following code,

self.navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController!.navigationBar.shadowImage = UIImage()
self.navigationController!.navigationBar.translucent = true

The result is image still below navigation bar and status bar even though I set the navigation bar to transparent.

enter image description here

Upvotes: 11

Views: 20243

Answers (4)

bikram sapkota
bikram sapkota

Reputation: 1124

If you are not using the default navigation bar, then shift your background image view (which is going to visible below the status bar) 20px up from the top constraint, then clear your status bar background color using:

 override func viewDidLoad() {
    super.viewDidLoad()

    let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
        statusBar?.backgroundColor = UIColor.clear
}

If you want to change the status bar item's color to white then use:

 override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

The output will be enter image description here

Upvotes: 12

Chris Herbst
Chris Herbst

Reputation: 1271

As per Dharmesh's answer, but updated for Swift 4

    self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController!.navigationBar.shadowImage = UIImage()
    self.navigationController!.navigationBar.isTranslucent = true

Upvotes: 1

minhazur
minhazur

Reputation: 4988

I solved this by setting transparent UIColor for status bar background.

    guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
                return
            }
            statusBar.backgroundColor = UIColor(red: 2, green: 200.0, blue: 200, alpha: 0) // color value has no effect. Only alpha value is needed to make it transparent

Upvotes: 1

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

I have tried same code as you provided:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    self.navigationController!.navigationBar.shadowImage = UIImage()
    self.navigationController!.navigationBar.translucent = true
}

And it is working fine and you can see result here:

enter image description here

Check my sample project and find out what are you missing.

Hope it will help.

Upvotes: 11

Related Questions