如何使UINavigationBar透明?虽然我希望它的栏项仍然可见。


当前回答

这适用于Swift 2.0。

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

其他回答

如果你使用最新的测试版iOS 13.4和Xcode 11.4进行构建,那么接受的答案将不再适用。 我找到了另一种方法,也许这只是测试版软件中的一个bug,但我把它写下来了,以防万一

(5)迅速

import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}

这适用于Swift 5。

// Clear the background image.
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)

// Clear the shadow image.
navigationController?.navigationBar.shadowImage = UIImage()

// Ensure the navigation bar is translucent.
navigationController?.navigationBar.isTranslucent = true

在Swift 4.2中

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

(在viewWillAppear中)然后在viewWillDisappear中,撤销它,put

self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.isTranslucent = false

在按照上面大家说的去做之后,也就是:

navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true

... 我的导航栏还是白色的。所以我加了这一行:

navigationController?.navigationBar.backgroundColor = .clear

... 果不其然!这似乎奏效了。

对于任何想在Swift 2.x中这样做的人:

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

或Swift 3.x:

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