如何更改UINavigationBar底部边框的颜色?

TIM*_*MEX 11 uinavigationbar uinavigationcontroller ios swift

我阅读了许多主题,但没有一个在最新版本的Swift的清晰,一致的答案中解决了这个问题.

例如,这个问题的最佳答案表明UINavigationBar.appearance().setShadowImage().但是,最新版本的swift中不存在这样的方法.

不想隐藏底部边框.我只是想改变颜色.

另外,能够改变高度会很棒,但我知道我在一个问题上问得太多了.

编辑:我创建了一个2x1像素图像并将其设置为shadowImage,但边框保持不变:

UINavigationBar.appearance().barTintColor = UIColor.whiteColor()
UINavigationBar.appearance().shadowImage = UIImage(named: "border.jpg") //in my AppDelegate, for global appearance
Run Code Online (Sandbox Code Playgroud)

这是图像; 它真的很小:边界图像

ZGs*_*ski 20

SWIFT 2.x:

出于方便,我已经扩展UIImage()到允许我基本上使用它作为颜色与下面的代码.

extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0, 0, 1.0, 0.5)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要在代码中添加以下行,以调整viewController的UINavigationBar阴影图像或此实例中的颜色.

// Sets Bar's Background Image (Color) //
self.navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.blueColor()), forBarMetrics: .Default)
// Sets Bar's Shadow Image (Color) //
self.navigationController?.navigationBar.shadowImage = UIImage.imageWithColor(UIColor.redColor())
Run Code Online (Sandbox Code Playgroud)

SWIFT 3.x/4.x:

扩展代码:

extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 0.5)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
Run Code Online (Sandbox Code Playgroud)

NavigationBar代码:

// Sets Bar's Background Image (Color) //
navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(color: .blue), for: .default)
// Sets Bar's Shadow Image (Color) //
navigationController?.navigationBar.shadowImage = UIImage.imageWithColor(color: .red)
Run Code Online (Sandbox Code Playgroud)

编辑1:

更新了扩展代码,因此您可以调整矩形大小而不更改UIImage颜色不透明度.

编辑2:

添加了Swift 3 + Swift 4代码.


cat*_*res 2

旧的 UIKit setter 方法UISomeClass.setSomething(whatIWantToSet)已被重新制定,以便您可以直接使用=符号设置它们。因此,在我的示例中,您必须使用UISomeClass.something = whatIWantToSet.

就你而言,它是UINavigationBar.appearance().shadowImage = whatYouWantToSet.