I'm trying to implement the delegation pattern on Swift. I have a main view controller and a "addInvoiceViewController" view controller which shows up when tapped on the plus button. I want to modify a list in the main view controller when tapped on a button in the "addInvoiceViewController".
Here is how I coded the main view controller (I inherited my protocol correctly) :
func addInvoice(name: String) {
invoices.append(name)
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! addInvoiceViewController
vc.delegate = self
}
Here is my "addInvoiceViewController" :
protocol AddInvoice: class {
func addInvoice(name: String)
}
class addInvoiceViewController: UIViewController {
weak var delegate: AddInvoice?
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func addInvoiceButton(_ sender: Any) {
if textField.text != "" {
delegate?.addInvoice(name: textField.text!)
self.dismiss(animated: true, completion: nil)
}
}
}
But the list hasn't been modified when tapped on the button (I know it because the list is connected to a tableview which shows the strings contained in the list)
I added the breakpoint in the viewDidLoad and checked what was delegate and here it is :
Here is cellFOrRowAt :
func numberOfSections(in tableView: UITableView) -> Int {
return invoicesSectionTitles.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let invoiceKey = invoicesSectionTitles[section]
if let invoiceValues = invoicesDictionary[invoiceKey] {
return invoiceValues.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let invoiceKey = invoicesSectionTitles[indexPath.section]
if let invoiceValues = invoicesDictionary[invoiceKey] {
cell.textLabel?.text = invoiceValues[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return invoicesSectionTitles[section]
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return invoicesSectionTitles
}