Morgan Wilde
Morgan Wilde

Reputation: 17323

UINavigationController back button title doesn't update dynamically

I have a text field in my view controller and I want to display a custom title for the back button. This is to represent changes made in the text field.

override func viewDidLoad() {
    super.viewDidLoad()
    // Update back button in the nav bar
    updateBackButton()

    // Text field delegation
    nameTextField.delegate = self
    nameTextField.addTarget(self, action: "updateBackButton", forControlEvents: .EditingChanged)
}
func updateBackButton() {
    let backButton = UIBarButtonItem(
        title: formHasChanged ? "Cancel" : "Back",
        style: .Done,
        target: nil,
        action: nil
    )
    print(backButton.title)
    navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}

This does effect the back button only once, in the viewDidLoad method. On subsequent calls to updateBackButton() there's no visible change, even though print(backButton.title) does print the appropriate output.

What's missing from my approach in order to have a dynamically updated back button title?

Output from the updateBackButton() method's print statement.

Optional("Back")
Optional("Cancel")
Optional("Back")
Optional("Cancel")
Optional("Back")

Upvotes: 1

Views: 585

Answers (1)

iRiziya
iRiziya

Reputation: 3245

If you want to call a function as an action from any control's target then you'll have to define it as @IBAction and use : while calling it. Just like

override func viewDidLoad() {
super.viewDidLoad()
// Update back button in the nav bar
//  updateBackButton() // Now you don't need to call it here, I guess..

// Text field delegation
nameTextField.delegate = self
nameTextField.addTarget(self, action: "updateBackButton:",forControlEvents: .EditingChanged)
}

@IBAction func updateBackButton(sender: AnyObject!) {
let backButton = UIBarButtonItem(
    title: formHasChanged ? "Cancel" : "Back",
    style: .Done,
    target: nil,
    action: nil
)
print(backButton.title!)
navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}

Update :

Try changing this line

navigationController?.navigationBar.topItem?.backBarButtonItem = backButton with navigationController?.navigationBar.topItem?.leftBarButtonItem = backButton or simply navigationItem.leftBarButtonItem = backButton

PS : It will not show you < symbol but I think you dont need it as you are dealing with cancel and done.

Its working now. Hope this will work for you too !

Upvotes: 1

Related Questions