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!
Swift 4+ version
alternative way: click on the navigation controller in storyboard (not the navigation controller in the UIViewController itself). Then, in the attributes section on the RHS you'll see back image and back mask. Set back image and you're done.
If you want to change the back button in every controller you can add this to app delegate in didFinishLaunchingWithOptions
//Here is the perfect solution To Set back button with Image and Action in default Navigation Bar
First add UIBarButton in Navigation bar
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
/Write on click action method/
To enable swipe to pop (back to previous controller), write two line code in ViewDidLoad method
And you will get perfect Back Button with Swipe to back animation
//Note:- To disable back button previous viewcontroller title , add one space in title text in back button in storyboard file inspector
In Swift 3.0 + put below code in
appdelegate
didFinishLaunchingWithOptions
method, it will work perfectlyThe last line will remove the title of
Navigation Back Button
if you don't want to remove title then just remove last line