在导航栏中添加彩色图像作为右侧栏按钮项

时间:2016-07-09 15:05:46

标签: ios swift uinavigationcontroller uinavigationitem

我添加了一个带有彩色背景图像的右侧导航栏项目:

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

navigationItem.rightBarButtonItem = rightButton

我没有将图像作为按钮的背景(颜色),而是获得了一个白色的占位符。

2 个答案:

答案 0 :(得分:3)

您可以将图像的渲染模式更新为 UIImageRenderingMode.alwaysOriginal

Swift 4:

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

斯威夫特3:

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

或者,您可以像弗拉基米尔的回答一样设置自定义视图。

答案 1 :(得分:1)

要实现此目的,您需要一个按钮UIButton,设置该按钮的图像,然后将其指定为自定义视图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