Reputation: 25
I want to be able to change the title displayed in the navigationBar
. I have the alertController
setup and it appears fine, however after inputting the newTitle text, the current title disappears but the new title doesn't appear. I have tried reloading data in the viewDidLoad
, viewWillAppear
, as well as in the button press event itself (as shown in code). Any input is appreciated.
@IBAction func changeTitleBarButtonPressed(_ sender: UIBarButtonItem) {
let titleChange = UIAlertController(
title: "Change Title",
message: "Please input text to change the title",
preferredStyle: .alert)
titleChange.addTextField { (textField) in
textField.placeholder = "Input new title"
}
titleChange.addAction(UIAlertAction(
title: "Cancel",
style: .cancel,
handler: { (cancelAction) in
titleChange.dismiss(animated: true)
}))
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = self.textField?.text
titleChange.dismiss(animated: true)
self.navigationItem.title = newTitle
self.imagesTableView.reloadData()
}))
self.present(titleChange, animated: true)
}
Upvotes: 2
Views: 93
Reputation: 119340
The only problem is you read the text
value from unrelated textField
(And its probably nil
or empty
). You may want to use the first textField
of the alert instead of self.textField?.text
:
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = titleChange.textFields![0].text // instead of `self.textField?.text`
titleChange.dismiss(animated: true) // this line is not required. You can get rid of it freely.
self.navigationItem.title = newTitle
}))
Make sure you are no setting the navigationItem.title
elsewhere (like viewWillAppear
or etc.)
Upvotes: 1