您的位置:首页 > 产品设计 > UI/UE

iOS开发小结 - UINavigationBar设置shadowImage

2016-07-11 23:35 537 查看

在项目中我们经常用到UINavigationBar,有时候我们需要设置UINavigationBar设置shadowImage,把下面的小黑条给弄掉,或者换一个颜色的阴影条,UINavigationBar有一个属性是shadowImage,然而发现设置了并没有用,下面描述一下怎么正确使用shadowImage属性。



我们先设置一下shadowImage为蓝色的图片,下面是代码:

let size = self.navigationController!.navigationBar.frame.size
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
var context = UIGraphicsGetCurrentContext()
UIColor.blueColor().setFill()
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, 2))
CGContextDrawPath(context, .Fill)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.navigationController?.navigationBar.shadowImage = image




设置完成后发现并没有效果,那是因为我们没有设置backgroundImage,我们先看一下apple官方对于这个属性的解释:

/* Default is nil. When non-nil, a custom shadow image to show instead of the default shadow image. For a custom shadow to be shown, a custom background image must also be set with -setBackgroundImage:forBarMetrics: (if the default background image is used, the default shadow image will be used).

大概意思就是像让shadowImage有作用,必须先设置backgroundImage,下面我们再实现一下一下代码,先设置backgroundImage为红色,然后再设置shadowImage:

let size = self.navigationController!.navigationBar.frame.size
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
var context = UIGraphicsGetCurrentContext()
UIColor.blueColor().setFill()
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, 2))
CGContextDrawPath(context, .Fill)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.navigationController?.navigationBar.shadowImage = image

UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.width+20), false, UIScreen.mainScreen().scale)
context = UIGraphicsGetCurrentContext()
UIColor.redColor().setFill()
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, size.height+20))
CGContextDrawPath(context, .Fill)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: .Default)




这下发现起作用了,同样的想要影藏navBar下面的小黑线,只需要将设置shadowImage成一个空的UIImage就行了:

self.navigationController?.navigationBar.shadowImage = UIImage()
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.width+20), false, UIScreen.mainScreen().scale)
var context = UIGraphicsGetCurrentContext()
UIColor.whiteColor().setFill()
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, size.height+20))
CGContextDrawPath(context, .Fill)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: .Default)





总结:想要设置shadowImage必须要先设置navigationBar的backgroundImage。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: