简体   繁体   中英

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.

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.

To achieve this you need a button UIButton , set the image of that button and then assigned it as the custom view if your UIBarButtonItem :

let button = UIButton()
button.frame = CGRectMake(0, 0, 51, 31)
button.setImage(UIImage(named: "avatar"), forState: .Normal)
button.addTarget(self, action: #selector(self.rightNavBarItemAction)), forControlEvents: .TouchUpInside)

let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM