Search code examples
iosswiftuinavigationcontrolleruinavigationitem

Add a colourful image as the right bar button item in a navigation bar


I add a right navigation bar item that has a coloured background image:

let rightButton = UIBarButtonItem(image: UIImage(named: "avatar")!,
                                  style: UIBarButtonItemStyle.Plain, 
                                  target: self,     
                                  action: #selector(self.rightNavBarItemAction))

navigationItem.rightBarButtonItem = rightButton

Instead of having the image as the background of the button (in colours), I get a white placeholder.


Solution

  • You can update the image's rendering mode to UIImageRenderingMode.alwaysOriginal.

    Swift 4.2:

    let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
    let rightButton = UIBarButtonItem(image: img,
                                          style: UIBarButtonItem.Style.Plain,
                                          target: self,
                                          action: #selector(self.rightNavBarItemAction))
    

    Swift 4:

    let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
    let rightButton = UIBarButtonItem(image: img,
                                          style: UIBarButtonItemStyle.Plain,
                                          target: self,
                                          action: #selector(self.rightNavBarItemAction))
    

    Swift 3:

    let img = UIImage(named: "avatar")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
    let rightButton = UIBarButtonItem(image: img,
                                          style: UIBarButtonItemStyle.Plain,
                                          target: self,
                                          action: #selector(self.rightNavBarItemAction))
    

    Alternatively you can set a custom view as in Vladimir's answer.