swift: setting back button image in nav bar

37,363

Solution 1

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.

Solution 2

In Swift 3.0 + put below code in appdelegate didFinishLaunchingWithOptions method, it will work perfectly

let backImage = UIImage(named: "BackNavigation")?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)

Or for Swift 4.0 +

let backImage = UIImage(named: "back-icon").withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -80.0), for: .default)

The last line will remove the title of Navigation Back Button if you don't want to remove title then just remove last line

Solution 3

If you want to change the back button in every controller you can add this to app delegate in didFinishLaunchingWithOptions

    let backImg: UIImage = UIImage(named: "back_button")!
    UIBarButtonItem.appearance().setBackButtonBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)

Solution 4

    self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back-icon")
    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back-icon")

Solution 5

//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

Share:
37,363
fuiiii
Author by

fuiiii

Updated on September 26, 2020

Comments

  • fuiiii
    fuiiii over 3 years

    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!

  • Yestay Muratov
    Yestay Muratov almost 9 years
    Hello, my image is stretched for some reason. What is the size of your image?
  • zevij
    zevij over 8 years
    Image is stretched because of the space allocated to the bar item by default. One way to get around this is to select the navigation item in storyboard and put a single space in 'Back Button' text box. Then, when you set an image it is limited to the remaining space...an alternative is to set a UIButton as the BarButton item.
  • Mehul
    Mehul over 7 years
    @goggelj, i have already set one space in storyboard in navigation bar -> back button. but image is stretched again. do you have any solution for that ?
  • zevij
    zevij over 7 years
    @mehul, If you have a bar item (inside bar button item) on the nav bar, select it and make sure it has a space too in 'title'
  • Mehul
    Mehul over 7 years
    @goggelj, thanks but i have checked and thanks for solution. thanks.
  • Nidhin
    Nidhin over 7 years
    @ChanchalRaj UIBarButtonItem.appearance().setBackButtonTitlePositionAdjus‌​tment(UIOffsetMake(0‌​, -60), for: UIBarMetrics.default) this will do the trick
  • Peter DeWeese
    Peter DeWeese over 7 years
    Please include searchable and selectable text for code instead of an image.
  • Tristan Newman
    Tristan Newman over 3 years
    Hey, I tried the above solution and the background image remained unchanged. Not sure where to go from here.
  • Shahid Aslam
    Shahid Aslam over 3 years
    Tristan please share your code snippet if not working also try to make sure you have added "back-icon" image in your solution ?