set navigationBar background image in swift

被刻印的时光 ゝ 提交于 2019-11-29 05:49:49
self.navigationController.navigationBar.setBackgroundImage(image, 
                                                   forBarMetrics: .Default)
William

In AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    //Image Background Navigation Bar
    let navBackgroundImage:UIImage! = UIImage(named: "backgroundNB.png")
    UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, forBarMetrics: .Default)

    return true
}

In Swift 3:

If you want to add a repeating image in the background you can make this call in AppDelegate > didFinishLaunchingWithOptions:

let image = UIImage(named: "imageNameInAsset")
UINavigationBar.appearance().setBackgroundImage(image, for: .default)

If you want to add an image to the center of the navigation bar you need to do this in the ViewController > viewWillAppear:

let titleView = UIImageView(image: UIImage(named: "imageNameInAsset"))
self.navigationItem.titleView = titleView

If you want to fill the image in navigation bar just use the code:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "your_Background_Image_Name")?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .default)
let navBackgroundImage:UIImage! = UIImage(named: "navbar_bg")

[UINavigationBar .appearance().setBackgroundImage(navBackgroundImage, forBarMetrics:.Default)]

For Swift 3:

In AppDelegate.swift:

UINavigationBar.appearance().setBackgroundImage(UIImage(named:"pattern.png"),
                                                                for: .default)

OR

In viewDidLoad():

self.navigationController?.navigationBar.setBackgroundImage(UIImage(named:"pattern.png"),
     for: .default)

Add the following code to didFinishLaunchingWithOptions method in AppDelegate.swift:

    if let myImage = UIImage(named: "navBarImage.jpg"){
        UINavigationBar.appearance().setBackgroundImage(myImage, for: .default)
    }

@benLIVE asked for how to do a back button, which I was doing when I found the accepted answer, so I thought I'd leave this here too (if a bit late) b/c if you are going to replace a nav bar icon, you may as well replace all of them!

    let cubeIcon = UIImageView(image: yourImage)
    cubeIcon.contentMode = .scaleAspectFit
    self.navigationItem.backBarButtonItem?.image = cubeIcon.image

set backgroundImage in Navigation controller

self.navigationController?.navigationBar .setBackgroundImage(UIImage(named: "cricket"), for: .default)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!