Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 487
fuiiii Avatar asked Jul 15 '14 23:07

fuiiii


People also ask

How do I customize the navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.


1 Answers

//Here is the perfect solution To Set back button with Image and Action in default Navigation Bar

First add UIBarButton in Navigation bar

enter image description here

Then Go to property in File inspector in storyboard and add space to hide back button title text

Set image in Ui Bar button image

enter image description here

/Write on click action method/

To enable swipe to pop (back to previous controller), write two line code in ViewDidLoad method

enter image description here

And you will get perfect Back Button with Swipe to back animation

enter image description here

//Note:- To disable back button previous viewcontroller title , add one space in title text in back button in storyboard file inspector

like image 143
Mehul Avatar answered Oct 21 '22 18:10

Mehul