How to hide UINavigationBar 1px bottom line

后端 未结 30 2128
不知归路
不知归路 2020-11-22 08:58

I have an app that sometimes needs its navigation bar to blend in with the content.

Does anyone know how to get rid of or to change color of this annoying little ba

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:36

    I use a UINavigationBar extension that enables me to hide/show that shadow using the UIAppearance API or selecting which navigation bar has to hide/show that shadow using Storyboard (or source code). Here is the extension:

    import UIKit
    
    private var flatAssociatedObjectKey: UInt8 = 0
    
    /*
      An extension that adds a "flat" field to UINavigationBar. This flag, when
      enabled, removes the shadow under the navigation bar.
     */
    @IBDesignable extension UINavigationBar {
        @IBInspectable var flat: Bool {
            get {
                guard let obj = objc_getAssociatedObject(self, &flatAssociatedObjectKey) as? NSNumber else {
                    return false
                }
                return obj.boolValue;
            }
    
            set {
                if (newValue) {
                    let void = UIImage()
                    setBackgroundImage(void, forBarPosition: .Any, barMetrics: .Default)
                    shadowImage = void
                } else {
                    setBackgroundImage(nil, forBarPosition: .Any, barMetrics: .Default)
                    shadowImage = nil
                }
                objc_setAssociatedObject(self, &flatAssociatedObjectKey, NSNumber(bool: newValue),
                        objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    

    Now, to disable the shadow across all navigation bars you have to use:

    UINavigationBar.appearance().flat = true
    

    Or you can enable/disable this behavior using storyboards:

提交回复
热议问题