1

I'm using Swift 3 and I have a problem. Indeed, I want to change programmatically my back button title, but it doesn't work anytime.

It works great when my title is short, but when the length is greater than 20 chars, it only display "Back".

To change the title, I use this in the parent controller:

let backItem = UIBarButtonItem()
backItem.title = "new name"
navigationItem.backBarButtonItem = backItem

Do you know why it doesn't display the title when it is long?

Thanks for your help

J. Doe
  • 141
  • 2
  • 10
  • 4
    That's normal behaviour. It takes in account available space, and has a kind of minimum font size. If possible, it's "< PreviousTitle CurrentTitle", but if it can't fit, but "Back" fits instead of "PreviousTitle", it's written "Back". It "Back" doesn't fit, it just "<". – Larme May 15 '17 at 12:57
  • 2
    see this once http://stackoverflow.com/questions/40504860/how-to-change-back-button-title-on-navigation-controller-in-swift3 – Anbu.Karthik May 15 '17 at 12:57
  • Thanks for your quick answers ! It is weird because it seems that there is space actually... Only the half of the navigation bar is busy at the limit of 20 chars. I will take a look at your question Anbu, thanks. – J. Doe May 15 '17 at 13:03
  • @Larme 's answer is right, it's system behavior – MoLice May 15 '17 at 13:13
  • I think it is not the best trick, but it works. I have created a button which contains the text that back button can't fit and I put this button as title with an action which reproduce back behavior (if I put this button as back button, it doesn't work) – J. Doe May 15 '17 at 13:51

2 Answers2

0

First you need to create property of UIButton in your controller

var btn1: UIButton!

Now you create UIBarButtonItem like this way

    btn1 = UIButton(type: .custom)
    btn1.setImage(UIImage(named: "imagename"), for: .normal)
    btn1.setTitle("Back", for: .normal)
    btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btn1.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside)

    navigationItem.backBarButtonItem = UIBarButtonItem(customView: btn1)

By using btn1 you can change title,image any time when you want.

jignesh Vadadoriya
  • 3,244
  • 3
  • 18
  • 29
0

You can change that in the parent view controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed
}
Joe
  • 8,868
  • 8
  • 37
  • 59
Rahul K Rajan
  • 776
  • 10
  • 19