estou tendo dificuldade com o conteúdo dessa aula. Tive que usar o "@objc" antes da função "showNewItem()", por um erro de compatibilidade sugerido pela IDE. Na ultima aula, enquanto essa função apenas pintava um algo na tela o código funcionava normalmente, porem depois que eu inseri na função o conteúdo proposto na aula:
let newItem = NewItemViewController()
if let navigation = navigationController {
navigation.pushViewController(newItem, animated: true)
}
A aplicação começou a crasear sempre que eu clico no botão "add new item" .
Segue todo o código do arquivo ViewController.swift:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var nameField : UITextField?
@IBOutlet var happinessField : UITextField?
var delegate: AddAMealDelegate?
var selected = Array<Item>()
var items = [
Item(name: "cheese", calories: 10),
Item(name: "pasta", calories: 10),
Item(name: "bread", calories: 10),
Item(name: "meat", calories: 10),
Item(name: "pepperoni", calories: 10)
]
override func viewDidLoad() {
let newItemButton = UIBarButtonItem(title: "add new item", style: UIBarButtonItem.Style.plain, target: self, action: #selector(showNewItem))
navigationItem.rightBarButtonItem = newItemButton
}
@objc func showNewItem() {
let newItem = NewItemViewController()
if let navigation = navigationController {
navigation.pushViewController(newItem, animated: true)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == UITableViewCell.AccessoryType.none {
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
let item = items[indexPath.row]
selected.append(item)
}
else {
cell.accessoryType = UITableViewCell.AccessoryType.none
let item = items[indexPath.row]
if let position = selected.index(of: item) {
selected.remove(at: position)
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let item = items[row]
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: nil)
cell.textLabel!.text = item.name
return cell
}
@IBAction func add() {
if (nameField == nil || happinessField == nil) {
return
}
let name:String = nameField!.text!
if let happiness = Int(happinessField!.text!) {
let meal = Meal(name: name, happiness: happiness, items: selected)
print("eaten \(meal.name) with happiness \(meal.happiness) with \(selected)")
if (delegate == nil) {
return
}
delegate!.add(meal)
if let navigation = navigationController {
navigation.popViewController(animated: true)
}
}
}
}