Convert remove navigationBar border to swift

2019-04-12 04:18发布

i'm trying to remove the navigationBar border in swift. This is done by using following code in objective-c:

[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault]

How can this be done in swift?

i've tried this, but not working:

UINavigationBar.appearance().shadowImage = UIImage(named: "")
UINavigationBar.appearance().setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default)

3条回答
地球回转人心会变
2楼-- · 2019-04-12 04:43

To change the background, text and icons colors, and also remove the border/shadow of the navigation bar via the appearance proxy, insert this code in the didFinishLaunchingWithOptions: of AppDelegate:

// our colors
let backgroundColor = UIColor.blueColor()
let foregroundColor = UIColor.whiteColor()

// status bar text color (.LightContent = white, .Default = black)
UIApplication.sharedApplication().statusBarStyle = .LightContent
// solid or translucent background?
UINavigationBar.appearance().translucent = false
// remove bottom shadow
UINavigationBar.appearance().shadowImage = UIImage()
// background color
UINavigationBar.appearance().setBackgroundImage(backgroundColor.toImage(), forBarMetrics: UIBarMetrics.Default)
// controls and icons color
UINavigationBar.appearance().tintColor = foregroundColor
// text color
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: foregroundColor]

Note: As you can see, we need to convert the UIColor to UIImage, so you can use this extension:

extension UIColor{
    func toImage() -> UIImage {
        let rect = CGRectMake(0, 0, 1, 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
        self.setFill()
        UIRectFill(rect)
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

Use it like this: UIColor.redColor().toImage()

查看更多
Fickle 薄情
3楼-- · 2019-04-12 04:47

I have used the below code to remove the navigation bar shadow from the app.

    self.navigationController?.navigationBar.clipsToBounds = true
查看更多
手持菜刀,她持情操
4楼-- · 2019-04-12 04:56

Try this:

UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
查看更多
登录 后发表回答