fuiiii fuiiii - 2 months ago 8
Swift Question

swift: setting back button image in nav bar

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)
}


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


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

Thanks!

Answer

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: image should be added to Images.xcassets folder, see sample code, UICatalog , for details.