消除 UINavigationBar 底部黑線

CuiXg 發表於 2020-10-17

1. 通過設定背景圖片與陰影圖片清除

// 在自定義 UINavigationController 內
self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationBar.shadowImage = UIImage()

2. 通過遍歷 UINavigationBar 子檢視,找到對應的 View,設定為隱藏

extension UINavigationBar {

    func hideBottomHairline() {
        findUnderImageView(self)?.isHidden = true
    }

    func showBottomHairline() {
        findUnderImageView(self)?.isHidden = true
    }


    func findUnderImageView(_ view: UIView) -> UIImageView? {

        if view is UIImageView && view.bounds.height <= 1.0 {
            return view as? UIImageView
        }

        for subView in view.subviews {
            return self.findUnderImageView(subView)
        }
        return nil
    }
}

使用時只需在 viewWillAppear 方法中新增 self.navigationController?.navigationBar.hideBottomHairline()