Swift 4
iOS 11.2
Xcode 9.2
TableViewController1 ---segue---> TableViewController2
You can change the text of the back button in either TableViewController1 or TableViewController2.
Change the back button text inside TableViewController1:
1) In viewWillAppear()
:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let myBackButton = UIBarButtonItem()
myBackButton.title = "Custom text"
navigationItem.backBarButtonItem = myBackButton
}
For some reason, viewDidLoad() is too early to add the back button to the NavigationItem. To connect the two TableViewControllers, in the storyboard control drag from the TableViewCell in TableViewController1 to the middle of TableViewController2 and in the popup menu select Selection Segue > Show
.
2) In tableView(_:didSelectRowAt:)
:
override func tableView(_ tableView: UITableView, didSelectRowAt: IndexPath) {
let myButton = UIBarButtonItem()
myButton.title = "Custom text"
navigationItem.backBarButtonItem = myButton
performSegue(withIdentifier: "ShowMyCustomBackButton", sender: nil)
}
To connect the two TableViewControllers, in the storyboard control drag from the little yellow circle above TableViewController1 to the middle of TableViewController2 and from the popup menu select Manual Segue > Show
. Then select the segue connecting the two TableViewControllers, and in the Attributes Inspector next to "Identifier" enter "ShowMyCustomBackButton".
3) In the storyboard
:
If you just need static custom text for the back button, select the NavigationItem for TableViewController1 (it has a <
for an icon in the storyboard’s table of contents), then open the Attributes Inspector and in the “Back Button” field enter your custom text (be sure to tab out of that field for the change to take effect).
Change the back button text inside TableViewController2:
1) In viewWillAppear()
:
class MySecondTableViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let myBackButton = UIBarButtonItem(
title: "<Custom text",
style: .plain,
target: self,
action: #selector(goBack) //selector() needs to be paired with an @objc label on the method
)
navigationItem.leftBarButtonItem = myBackButton
}
@objc func goBack() {
navigationController?.popViewController(animated: true)
}
To connect the two TableViewControllers, in the storyboard control drag from the TableViewCell in TableViewController1 to the middle of TableViewController2 and in the popup menu select Selection Segue > Show
.