Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set navigationBar background image in swift

Code below is not working for me, can anyone help to figure it out what is wrong?

var image = UIImage(named: "10384605_10152519403846670_5189785375955620548_n.jpg") as UIImage

self.navigationController.navigationBar.setBackgroundImage(image , forBarMetrics:UIBarMetrics)
like image 921
Rohit Avatar asked Jun 20 '14 13:06

Rohit


3 Answers

self.navigationController.navigationBar.setBackgroundImage(image, 
                                                   forBarMetrics: .Default)
like image 119
B.S. Avatar answered Nov 07 '22 04:11

B.S.


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
}
like image 16
William Avatar answered Nov 07 '22 04:11

William


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
like image 13
Daniel Nord Avatar answered Nov 07 '22 03:11

Daniel Nord