71

I need to customise the look of a back button in a Swift project.

Here's what I have: Default Back Button

Here's what I want: Custom Back Button

I've tried creating my own UIBarButtonItem but I can't figure out how to get the image to be beside the text, rather than as a background or a replacement for the text.

let backButton = UIBarButtonItem(title: "Custom", style: .Plain, target: self, action: nil    )
//backButton.image = UIImage(named: "imageName") //Replaces title
backButton.setBackgroundImage(UIImage(named: "imageName"), forState: .Normal, barMetrics: .Default) // Stretches image
navigationItem.setLeftBarButtonItem(backButton, animated: false)
Conor
  • 1,007
  • 1
  • 10
  • 16

17 Answers17

106

You can do something like that:

let yourBackImage = UIImage(named: "back_button_image")
self.navigationController?.navigationBar.backIndicatorImage = yourBackImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
self.navigationController?.navigationBar.backItem?.title = "Custom"

Your image will only have one color though

Randy
  • 4,335
  • 3
  • 30
  • 64
  • 12
    Mostly worked, the title of the button didn't change. let yourBackImage = UIImage(named: "back_button_image") self.navigationController?.navigationBar.backIndicatorImage = yourBackImage self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage self.navigationController?.navigationBar.backItem?.title = "Custom" – Conor May 31 '16 at 20:21
  • 2
    My back button ends up in the center of the screen? Any thoughts? – mnearents Dec 12 '17 at 05:38
  • @lusus_vir Did you end up fixing this issue? I'm seeing the same result. – Cole Roberts Aug 21 '18 at 17:44
  • 1
    I there, if I use this code, this will change every back icon for the controllers that belongs to the same navigation controller, so how can I manage this behavior to only change the back button image in one controller in the same navigation controller? I try to put in a buffer the original content of self.navigationController?.navigationBar.backIndicatorImage, but its null – PatricioS May 14 '19 at 19:47
  • I've missed "backIndicatorTransitionMaskImage". Thank you, you saved me a lot of time. – Vladimir Sukanica Jun 15 '21 at 13:23
44

Note: Please remember that the back button belongs to the the source ViewController and not to the destination ViewController. Thus, the modification needs to be done in the source VC, which is reflected to all the view in the navigation controller

Code Snippet:

let backImage = UIImage(named: "icon-back")

self.navigationController?.navigationBar.backIndicatorImage = backImage

self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage

/*** If needed Assign Title Here ***/
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
Supratik Majumdar
  • 2,365
  • 1
  • 23
  • 31
32

swift 4

In my case, I needed to have only the image of the button, without any text. I hope this will be useful to someone.

let imgBackArrow = UIImage(named: "back_arrow_32")

navigationController?.navigationBar.backIndicatorImage = imgBackArrow
navigationController?.navigationBar.backIndicatorTransitionMaskImage = imgBackArrow

navigationItem.leftItemsSupplementBackButton = true
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)

For iOS 12 you can do

func setNavigationBar() {

    self.navigationItem.setHidesBackButton(true, animated:false)

    //your custom view for back image with custom size
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))

    if let imgBackArrow = UIImage(named: "icn_back_arrow") {
        imageView.image = imgBackArrow
    }
    view.addSubview(imageView)

    let backTap = UITapGestureRecognizer(target: self, action: #selector(backToMain))
    view?.addGestureRecognizer(backTap)

    let leftBarButtonItem = UIBarButtonItem(customView: view ?? UIView())
    self.navigationItem.leftBarButtonItem = leftBarButtonItem
}

@objc func backToMain() {
    self.navigationController?.popViewController(animated: true)
}
Booharin
  • 753
  • 10
  • 10
12

For setting custom back bar button and remove text from back bar button, FROM STORYBOARD only, without any coding.


For setting custom back button and remove text from back button

RESULT:

enter image description here

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Mushrankhan
  • 749
  • 9
  • 12
11

For the back button image:

  • By this tutorial: (but didn't work for me)

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "imageName")
    
  • But this stack answer: (worked for me)

    var backButtonImage = UIImage(named: "back-button-image")
    backButtonImage = backButtonImage?.stretchableImage(withLeftCapWidth: 15, topCapHeight: 30)
    UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
    

And for the font, assuming you want the font to match for the whole navigation bar:(currently in use)

if let font = UIFont(name: "Avenir-Book", size: 22) {
  UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font]
}
Vinoth Vino
  • 9,166
  • 3
  • 66
  • 70
Idan
  • 5,405
  • 7
  • 35
  • 52
  • 3
    Also add `UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "imageName")`, and it will work. – Jay Lee Aug 19 '19 at 04:02
11

Having a button in Navigation Bar with Image AND Text is quite hard. Especially after they have introduced a new headache with UIBarButtonItem position in iOS 11: iOS 11 - UIBarButtonItem horizontal position

You can make either button with image or a button with text, but not a button with both of those. I even tried two UIBarButtonItems together, one with image and other with text - it still doesn't look good at all and their UIStackView can't be easily accessed for modification.

Unexpectedly I found a plain simple solution:

1) design the button as view in Interface Builder. In my case it is inside target UIViewController and accessible via IBOutlet for simplicity

2) set Leading Space constraint for the image to be negative, you might also want to set view's background color to .clear.

enter image description here

3) use it:

@IBOutlet var backButtonView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    let backButton = UIBarButtonItem(customView: self.backButtonView)
    self.backButtonView.heightAnchor.constraint(equalToConstant: 44).isActive = true // if you set more than you'll get "Unable to simultaneously..."
    self.backButtonView.widthAnchor.constraint(equalToConstant: 75).isActive = true
    self.navigationItem.leftBarButtonItem = backButton
}

That's it. No need to use the trick with negative spacer for iOS 10 or the trick with imageInsets for iOS 11 (which works only if you have image and doesn't work for image+text, BTW).

enter image description here

WINSergey
  • 1,977
  • 27
  • 39
Vitalii
  • 4,267
  • 1
  • 40
  • 45
  • In my case arrow hit area is working a bit strange (only the right part can be touched). And also you have 2 separate buttons so it doesn't work the same, it only look the same. – Makalele Oct 23 '18 at 07:17
9

I have tried all the above and all make the custom image without changing the text The only one worked for me is from this answer

let backBTN = UIBarButtonItem(image: UIImage(named: "Back"), 
                              style: .plain, 
                              target: navigationController, 
                              action: #selector(UINavigationController.popViewController(animated:)))
navigationItem.leftBarButtonItem = backBTN
navigationController?.interactivePopGestureRecognizer?.delegate = self
Mohamed Saleh
  • 2,881
  • 1
  • 23
  • 35
5

swift 3

    extension UIViewController {

        func setBackButton(){
            let yourBackImage = UIImage(named: "backbutton")
            navigationController?.navigationBar.backIndicatorImage = yourBackImage
            navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
        }

    }
Elijah
  • 8,381
  • 2
  • 55
  • 49
Ahmed Safadi
  • 4,402
  • 37
  • 33
5

I know it was answered. Here you can set title, image and target.

    let view = UIView()
    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "backArrow_theme"), for: .normal)
    button.setTitle("Back to workflow", for: .normal)
    button.addTarget(self, action: #selector(onBackButton(_:)), for: .touchUpInside)
    button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
    button.sizeToFit()
    view.addSubview(button)
    view.frame = button.bounds
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: view)
Muruganandham K
  • 5,271
  • 5
  • 34
  • 62
  • 1
    In my case, I dont need text for backbutton. Just replacing the text with blank space, didn't fixed the issue completely. Back button is still blue. I have used the following code to get the desired color. navigationController?.navigationBar.barTintColor = .black navigationController?.navigationBar.tintColor = .black – Sravan Aug 09 '22 at 12:25
  • Perfect! Much more flexible like this. – Siamaster Oct 24 '22 at 12:49
4

This worked for me on iOS 13 using swift 5. Just hide the original back button and add a new navigation left bar button item with an action.

navigationItem.hidesBackButton = true
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "backBtn"), style: .plain, target: self, action: #selector(back(sender:)))

@objc func back(sender: UIBarButtonItem) {
    self.navigationController?.popViewController(animated:true)
}
Kegham K.
  • 1,589
  • 22
  • 40
  • 1
    This is simple and works, but not perfect. The leftBarButtonItem will be a bit to the right of the back buttons original position. If this is acceptable, then go ahead and use it. – Géza Mikló Jan 27 '20 at 15:30
2

Just replace the backButton with a custom rightBarButtonItem

let backImage = UIImage(named: "BackBtn")?.withRenderingMode(.alwaysOriginal)
    navigationItem.leftBarButtonItem = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(popnav))

    @objc func popnav() {
    self.navigationController?.popViewController(animated: true)
}
Mohamed Ali
  • 263
  • 3
  • 13
1

Swift 4.2 Add this functions ViewController

func addNavigationBarButton(imageName:String,direction:direction){
    var image = UIImage(named: imageName)
    image = image?.withRenderingMode(.alwaysOriginal)
    switch direction {
    case .left:
       self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    case .right:
       self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    }
}

@objc func goBack() {
    navigationController?.popViewController(animated: true)
}

enum direction {
    case right
    case left
}

Using you should use here

viewDidLoad()

addNavigationBarButton(imageName: "ic_back", direction:.left)
ikbal
  • 1,110
  • 12
  • 21
1

Just in case someone need to change all Back buttons color or font with Swift5. UIBarButtonItem.appearance().tintColor = .red

Add this to AppDelegate.swift file.

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    // Override point for customization after application launch.        
    UIBarButtonItem.appearance().tintColor = .white
    UIBarButtonItem.appearance().setTitleTextAttributes([
        NSAttributedString.Key.foregroundColor: .red,
        NSAttributedString.Key.font: UIFont(name: "font_name", size: 14)!
    ], for: .normal)

    return true
}

}
J A S K I E R
  • 1,976
  • 3
  • 24
  • 42
1

iOS13 And Later, Try to use UINavigationBarAppearance

let appearance = UINavigationBarAppearance()
// set back image
appearance.setBackIndicatorImage(UIImage(named: "back_icon"), transitionMaskImage: UIImage(named: "back_icon"))

// set appearance to one NavigationController
let navVC = UINavigationController()
navVC.navigationBar.standardAppearance = appearance
navVC.navigationBar.scrollEdgeAppearance = appearance

// or you can config for all navigation bar
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance

back title base on you Viewcontroller

viewController.navigationItem.backButtonTitle = "your back title"
wlixcc
  • 1,132
  • 10
  • 14
0

Changing the navigation controller`s standardAppearance or scrollEdgeAppearance will reset your custom backIndicatorImage and backIndicatorTransitionMaskImage

let backImage = UIImage(systemName: "chevron.left.circle.fill")
navigationController?.navigationBar.backIndicatorImage = backImage
navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage

// this will cause the backIndicatorImage to be reset
let standardAppearance = UINavigationBarAppearance()
navigationController?.standardAppearance = standardAppearance

To change the backIndicatorImage in conjunction with UINavigationBarAppearance you will need to set the backImage using this:

navigationController?.standardAppearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)
nayooti
  • 395
  • 2
  • 15
0
    let rectInsets = UIEdgeInsets(top: 0, left: -1, bottom: 0, right: 0)
    let backButton = Asset.Assets.backArrow.image.withAlignmentRectInsets(rectInsets)
    
    let appearance = UINavigationBarAppearance()
// if you need to hide the back button text
        appearance.backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.clear]
// set costume back button image
    appearance.setBackIndicatorImage(backButton, transitionMaskImage: backButton)
        UINavigationBar.appearance().standardAppearance = appearance
Valeriy
  • 723
  • 6
  • 17
-1

You can change it globally in the AppDelegate with the following code:

UINavigationBar.appearance().backIndicatorImage = UIImage(named: "custom-back")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "custom-back")
Ing. Ron
  • 2,005
  • 2
  • 17
  • 33