在导航栏中设置按钮图像

在导航栏中设置按钮图像

本文介绍了swift:在导航栏中设置按钮图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在控制器的导航栏中设置后退按钮图像,这是我在viewDidLoad()中的代码:

I'm trying to set the back button image in nav bar in my controller, here's my code in viewDidLoad():

        var backImg: UIImage? = UIImage(named: "back_btn.png")
    println(backImg)
    if var back_img = backImg  {
        println("GET IT")
        println(back_img)
        println(UIControlState.Normal)
        println(UIBarMetrics.Default)
    self.navigationController.navigationBar.backItem.backBarButtonItem.setBackButtonBackgroundImage(back_img, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
    }

我试图把它们放到viewWillLoad,但得到同样的错误

I tried to put them to viewWillLoad, but getting the same error

控制台显示错误消息:

<UIImage: 0x7ff37bd85750>
GET IT
<UIImage: 0x7ff37bd85750>
VSC14UIControlState (has 1 child)
(Enum Value)
fatal error: unexpectedly found nil while unwrapping an Optional value

我不知道哪个部分出了问题。好像back_img不是零,但我得错误说它是零

I don't know which part went wrong. Seems like the back_img is not nil, but I got error saying it's nil

谢谢!

推荐答案

我已经通过查看示例代码找到了答案。
1)在故事板中创建一个条形按钮项。
2)使用IBOutlet将该按钮链接到控制器
3)将图像添加到按钮

I have figured out by looking into sample code.1) Create a bar button item in storyboard.2) Link that button to controller using IBOutlet3) Add image to the button

 var backImg: UIImage = UIImage(named: "back_btn")
 backBtn.setBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)

PS:图像应该添加到Images.xcassets文件夹中,参见示例代码,,了解详情。

PS: image should be added to Images.xcassets folder, see sample code, UICatalog , for details.

这篇关于swift:在导航栏中设置按钮图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:23