Reputation: 927
I have one view controller with a button that when clicked goes to a second view controller with a table view. The two scenes are linked through storyboard, as Present Modally. I want the text of the button in the first view controller to change when a row is selected in the table view of the second view controller.
Is there a reason why the button is not changing when the cell is selected?
Any help would be greatly appreciated, I'm still a beginner with Swift.
Below are the relevant lines of code:
View Controller 1
class ChartsViewController: UIViewController {
@IBOutlet weak var titleButton: UIButton!
}
extension ChartsViewController: ModalDelegate {
func didSelectValue(value: String) {
self.titleButton.setTitle(value, for: .normal)
}
}
View Controller 2
protocol ModalDelegate: class {
func didSelectValue(value: String)
}
class DashboardModalViewController: UIViewController {
var delegate: ModalDelegate?
}
extension DashboardModalViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let rowTitle = self.rows[indexPath.row].text
print (rowTitle)
delegate?.didSelectValue(value: rowTitle)
dismiss(animated: true, completion: nil)
}
}
Upvotes: 1
Views: 505
Reputation: 6648
I think you need to set the second controller's delegate in View Controller 1's prepare
method for segue like:
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dashboardModalViewController = segue.destination as? DashboardModalViewController {
dashboardModalViewController.delegate = self
}
}
Upvotes: 2