导航栏按钮图像

时间:2015-02-03 12:53:18

标签: ios swift uinavigationcontroller uinavigationbar

我正在使用此代码在导航栏上获取徽标。

override func viewDidAppear(animated: Bool) {

    let image = UIImage(named: "LogoWithTextSmaller.png")
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
    }

这很好,但徽标没有任何颜色 - 除了'蓝色'。是因为它是一个png文件。有什么我可以保留原始颜色

我做到了:

self.navigationItem.titleView = UIImageView(image: image)

并将图像带到导航栏上,颜色正确 - 但它位于中间,我希望它在左侧。

6 个答案:

答案 0 :(得分:26)

您需要声明图像始终保持原始状态。所以添加如下代码

var image = UIImage(named: "image-name")
image = image?.withRenderingMode(.alwaysOriginal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: nil)

答案 1 :(得分:3)

Swift 3 中,使用以下语法

可以完成相同的操作
var image = UIImage(named: "Filter")
image = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image:image , style: UIBarButtonItemStyle.plain, target: nil, action: nil)

答案 2 :(得分:1)

Swift 3.0

let btnLogo = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
btnLogo.setTitle("", for: .normal)
btnLogo.backgroundColor = UIColor.clear
btnLogo.layer.cornerRadius = 4.0
btnLogo.layer.masksToBounds = true

var imageLogo = UIImage(named: "LogoWithTextSmaller.png")
imageLogo = imageLogo?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
btnLogo.setImage(imageLogo, for: .normal)

let barButton = UIBarButtonItem(customView: btnLogo)
self.navigationItem.leftBarButtonItem = barButton

swift 2.0

var image = UIImage(named: "Filter")
image = image?.imageWithRenderingMode(UIImageRenderingMode.alwaysOriginal)

<强>目标C

 UIImage *image = [[UIImage alloc] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

 UIBarButtonItem *_btnLeftBar = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"LogoWithTextSmaller.png"]
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(yourMethod)];

 self.navigationItem.rightBarButtonItem= _btnLeftBar;

对于withRenderingMode(_ :)详细信息,请参阅下面的apple文档链接 https://developer.apple.com/documentation/uikit/uiimage/1624153-withrenderingmode

答案 3 :(得分:0)

在swift 3.0中

treelist

答案 4 :(得分:0)

Swift 3 如果缺少该物品,可以尝试一下。

  let navigationBar = navigationController?.navigationBar
  let topItem = navigationBar?.topItem
  var navigateimage = UIImage(named: "addConnectionFromSupport")
  navigateimage = navigateimage?.withRenderingMode(.alwaysOriginal)
  topItem?.rightBarButtonItem = UIBarButtonItem(image: navigateimage, style:.plain, target: nil, action: nil)

答案 5 :(得分:0)

SWIFT 4

    let back = UIImage(named: "back_white")?.withRenderingMode(.alwaysOriginal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: back, style:.plain, target: nil, action: nil)