Jose Tovar
Jose Tovar

Reputation: 189

UINavigationBar set background image center swift..?

I'm placing the background image this:

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

but, repeat the image. No I want it to be repeated to me and Put it center.. ?

Upvotes: 2

Views: 1214

Answers (2)

Karoly Nyisztor
Karoly Nyisztor

Reputation: 3595

Here's how to fix it using UIAppearance and UIImage API:

// disable image stretching by defining left and top caps. 
let navbarImage = image.stretchableImage(withLeftCapWidth: 1, topCapHeight: 1)
UINavigationBar.appearance().setBackgroundImage(navbarImage, for: .default)

Example before: enter image description here

and after the fix: enter image description here

Upvotes: 5

Abhishek Sharma
Abhishek Sharma

Reputation: 3283

Try with below method which worked for me.

        var headerview = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 44))            
        let imgview = UIImageView(frame: CGRect(x: 75, y: 0, width: 150, height: 44))
        imgview.image = UIImage(named: "ImageName")
        imgview.contentMode = UIViewContentMode.scaleAspectFit
        headerview.addSubview(imgview)
        self.navigationController?.navigationBar.topItem?.titleView = headerview

Upvotes: 1

Related Questions