0

I want customised navigation bar back button title with action.

My Image :

enter image description here

I need back button like this. Here i added text successfully, but not back arrow. Here my code has action for back button.

This is my code

    //Custom barButtonItem with custom alert function
    self.navigationItem.hidesBackButton = true
    let newBackButton = UIBarButtonItem(title: "< Dialer", style: .plain, target: self, action: #selector(back(sender:)))
    self.navigationItem.leftBarButtonItem = newBackButton

When i add above code it's getting like this. enter image description here

Naresh
  • 16,698
  • 6
  • 112
  • 113
  • I tried `NSMutableAttributedString` but it's not working. My code is `let attrString = NSMutableAttributedString(string: "<", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]) attrString.append(NSMutableAttributedString(string: " Dialer", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)]))` – Naresh Sep 04 '19 at 11:26
  • `let newBackButton = UIBarButtonItem(title: "\(attrString)", style: .plain, target: self, action: #selector(back(sender:)))` – Naresh Sep 04 '19 at 11:26
  • This code helps a lot for me .... https://stackoverflow.com/questions/27499998/how-to-set-image-for-bar-button-with-swift/35233701 – Naresh Sep 04 '19 at 13:12

1 Answers1

0
func backButtonConfiguration(_ title : String, backImageName : String) {
    let backImage : UIImage = UIImage(named: backImageName)!
    self.navigationBar.backIndicatorImage = backImage.withRenderingMode(.alwaysTemplate)
    self.navigationBar.backIndicatorTransitionMaskImage = backImage
    self.navigationBar.backItem?.title = title
}

Update

if we need custom action for back button then we have to add custom BarButtonItem. And if we need bar back button look same as built in back button then we can create custom view and use it it as a bar button item

  weak var customView : UIView!

  lazy var leftBarButtonView : UIBarButtonItem! = {
    let btnBack = UIBarButtonItem(customView: customView)
    let gesture = UITapGestureRecognizer(target: self, action: #selector(btnButtonClicked(_:)))
    gesture.numberOfTapsRequired = 1
    self.customView.addGestureRecognizer(gesture)
    self.customView.isUserInteractionEnabled = true
    return btnBack
  }()

  @objc func btnButtonClicked(_ gesture : UITapGestureRecognizer) {
    self.navigationController?.popViewController(animated: true)
  }

 self.navigationItem.leftBarButtonItems = [leftBarButtonView]
Pratik Sodha
  • 3,679
  • 2
  • 19
  • 38