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

时间:2016-05-16 19:16:11

标签: ios swift uinavigationcontroller uinavigationbar

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

例如,this question的最佳答案显示UINavigationBar.appearance().setShadowImage()。但是,最新版本的swift中不存在这样的方法。

不想隐藏底部边框。我只想更改颜色

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

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

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

这是图像;它真的很小:border image

3 个答案:

答案 0 :(得分:19)

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
    }
}

接下来,您需要在代码中添加以下行以调整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())

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
    }
}

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)

修改1:

更新了扩展程序代码,因此您可以在不更改UIImage颜色不透明度的情况下调整矩形大小。

编辑2:

添加了Swift 3 + Swift 4代码。

答案 1 :(得分:1)

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

在您的情况下,它是UINavigationBar.appearance().shadowImage = whatYouWantToSet

答案 2 :(得分:0)

有点棘手的解决方案,但是它不需要编码和扩展即可工作。只需在NavigationBar下的StoryBoard中添加一个Progress View,然后将其颜色和高度设置为您喜欢的任何颜色。如果要使用全边框,请将进度设置为1。

enter image description here

因此,您将为导航栏获得适当的边框,并可以选择随时添加progressView作为额外的奖励。 我知道,我知道...有点棘手,但是程序员应该很懒,不是吗?

相关问题