Fiz tudo conforme o video, no entanto, ainda assim continua aparecendo esse erro ao declarar o delegate: self no inicializador.
Erro: Incorrect argument label in call (have 'delegate:', expected 'coder:') Replace 'delegate' with 'coder'
E mesmo se eu troque o delegate por coder, aparece esse erro: Cannot convert value of type 'ViewController' to expected argument type 'NSCoder'
ViewController
@IBOutlet var tableView: UITableView?
func add(_ item: Item) {
items.append(item)
if let table = tableView {
table.reloadData()
}
}
override func viewDidLoad() {
let newItemButton = UIBarButtonItem(title: "new item",
style: UIBarButtonItem.Style.plain, target: self,
action: #selector(showNewItem))
navigationItem.rightBarButtonItem = newItemButton
}
@objc func showNewItem() {
let newItem = NewItemViewController(delegate: self)
if let navigation = navigationController {
navigation.pushViewController(newItem, animated:
true)
}
}
NewItemViewController
class NewItemViewController: UIViewController {
class NewItemViewController: UIViewController {
var delegate:AddAnItemDelegate?
init(delegate: AddAnItemDelegate){
super.init(nibName: "NewItemViewController", bundle: nil)
self.delegate = delegate
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBOutlet var nameField : UITextField?
@IBOutlet var caloriesField : UITextField?
@IBAction func addNewItem(){
let name = nameField!.text
let calories = Double(caloriesField!.text!)
if (name == nil || calories == nil || delegate == nil) {
return
}
let item = Item(name: name!, calories: calories!)
delegate!.add(item)
if let navigation = navigationController{
navigation.popViewController(animated: true)
}
}
AddAnItemDelegate
import Foundation
protocol AddAnItemDelegate {
func add(_ item: Item)
}