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


当前回答

解决方案- Swift 5 - iOS 13+

根据文档,在你的UIViewController子类中:

override func viewDidLoad()
{
    super.viewDidLoad()
    
    let appearance = UINavigationBarAppearance()
    appearance.configureWithTransparentBackground()
    //appearance.backgroundColor = UIColor.clear
    
    navigationItem.compactAppearance = appearance
    navigationItem.scrollEdgeAppearance = appearance
    navigationItem.standardAppearance = appearance
    
    //...
}

只是为了澄清,这使得UINavigationBar完全透明。栏按钮项仍然可见,并正常工作。

什么不起作用

override func viewDidLoad()
{
    super.viewDidLoad()
    
    navigationController?.navigationBar.isTranslucent = true
    navigationController?.navigationBar.isOpaque = false

    //...
}

这让我意识到我其实不知道透明RIP和半透明RIP之间的区别。

参考文献

https://developer.apple.com/documentation/uikit/uinavigationcontroller/customizing_your_app_s_navigation_bar

https://www.lexico.com/en/definition/transparent

https://www.lexico.com/en/definition/translucent

更新08/10/2021

在以我提供的方式设置外观后,更改navigationItem栏按钮将重置外观,您必须再次执行此操作。

其他回答

在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

另一种方式,为我工作是子类UINavigationBar和留下drawRect方法空!!

@IBDesignable class MONavigationBar: UINavigationBar {


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
    // Drawing code
}}

这适用于Swift 2.0。

navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.translucent = true
extension UINavigationBar {
var isTransperent: Bool {
        get {
            return false // Just to satisfy property
        }
        set {
            if newValue {
                self.shadowImage = UIImage()
                self.isTranslucent = true
                self.setBackgroundImage(UIImage(), for: .default)
            } else {
                self.shadowImage = UIImage()
                self.isTranslucent = false
                self.setBackgroundImage(nil, for: .default)
            }
        }
    }
}

这适用于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