swift:在导航栏中设置后退按钮图像

2023-06-12移动开发问题
1

本文介绍了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

带有错误消息的控制台:

Console with error message:

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

我不知道哪一部分出了问题.似乎 back_img 不是 nil,但我收到错误说它是 nil

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 IBOutlet 3) Add image to the button

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

PS:图片应添加到 Images.xcassets 文件夹,请参阅示例代码,UICatalog,了解详情.

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

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

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

[ios.cocos2d+box2d]如何禁用自动旋转?
[ios.cocos2d+box2d]how to disable auto-rotation?([ios.cocos2d+box2d]如何禁用自动旋转?)...
2024-08-12 移动开发问题
7

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?
How can I implement a virtual joystick for a cocos2d game outside the cocos2d environment?(如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?)...
2024-08-12 移动开发问题
13