Changing Navigation bar back button title in run time.

Hi, I'm currently working on changing navigation bar back button in run time. However it doesn't work.

Below is the code where i want to change my back button title.

What I want to do is if I scroll more than hightCheck i want to make my backButton title to be "back", else " ".

The method for changing back button title seems to work in the first time when the view loads up, but does not change after all.

Is it to change back Button title in run time?


override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let a = tableView.tableHeaderView?.subviews[1]
     
    let heightCheck = tableView.bounds.origin.y + a!.frame.height + navigationController!.navigationBar.frame.height
    var backButtonTitle = " "

    if heightCheck > a!.frame.origin.y{
      backButtonTitle = "back" 
    }else{
      backButtonTitle = " "
    }

    navigationController?.navigationBar.topItem?.backButtonTitle = backButtonTitle
  }
Answered by Claude31 in 661101022
What I do usually:
  • create a Bar Button Item that I put in the left place.

  • Connect to an IBOutlet

Code Block
    @IBOutlet fileprivate weak var backButton: UIBarButtonItem!
  • Then change its title:

Code Block
backButton.title = heightCheck > a!.frame.origin.y ? NSLocalizedString("back", comment: "") : ""


Accepted Answer
What I do usually:
  • create a Bar Button Item that I put in the left place.

  • Connect to an IBOutlet

Code Block
    @IBOutlet fileprivate weak var backButton: UIBarButtonItem!
  • Then change its title:

Code Block
backButton.title = heightCheck > a!.frame.origin.y ? NSLocalizedString("back", comment: "") : ""


The back button in the UINavigationBar under control of UINavigationView is constructed based on the settings of the previous view controller.

Please try this:
Code Block
        self.navigationController?.navigationBar.backItem?.backButtonTitle = backButtonTitle

(Not topItem, but backItem. Modifying topItem would be effective only before the navigation takes place.)


By the way, your question is not related to the SwiftUI framework and the tag SwiftUI is not appropriate. Better use UIKit instead.
Thanks for the answer, backItem method solved my problem. Mistakenly put solved batch to different person, sorry for that...
I guess i have to read more documentation:). By the way sorry for the SwiftUI tag.
Changing Navigation bar back button title in run time.
 
 
Q