O meu programa compila, porém quando vou adicionar um novo item(nome e caloria) o novo nome não aparece na lista inicial de refeição do meu programa. Alguém pode me ajudar?
Segue abaixo o código da minha ViewController:
import UIKit
protocol AddAMealDelegate{
func add(meal:Meal)
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AddAnItemDelegate {
@IBOutlet var nameField:UITextField?
@IBOutlet var happinessField:UITextField?
@IBOutlet var tableView :UITableView?
var delegate:AddAMealDelegate?
var items = [
Item(name: "Strogonoff", calories:400),
Item(name: "Batata Palha", calories:100),
Item(name: "Cookie", calories:220),
Item(name: "Coconut Oil", calories:125),
Item(name: "Chocolate Frosting", calories:559),
Item(name: "Chocolate Chip", calories:431)
]
override func viewDidLoad() {
let newItemButton = UIBarButtonItem(title: "new item",
style: UIBarButtonItemStyle.Plain,
target: self,
action: Selector("showNewItem"))
navigationItem.rightBarButtonItem = newItemButton
}
func add(item: Item) {
items.append(item)
if tableView == nil{
return
}
tableView!.reloadData()
}
func showNewItem() {
let newItem = NewItemViewController(delegate: self)
newItem.delegate = self
if let navigation = navigationController {
navigation.pushViewController(newItem, animated: true)
}
}
var selected = Array<Item>()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let item = items[row]
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel!.text = item.name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell == nil {
return
}
var item = items[indexPath.row]
if cell!.accessoryType == UITableViewCellAccessoryType.None{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
selected.append(item)
}
else{
cell!.accessoryType = UITableViewCellAccessoryType.None
if let position = selected.indexOf(items[indexPath.row]) {
selected.removeAtIndex(position)
}
}
}
@IBAction func add(){
if nameField == nil || happinessField == nil{
return
}
let name = nameField!.text
let happiness = Int (happinessField!.text!)
if happiness == nil{
return
}
let meal = Meal(name: name!,happiness:happiness!)
meal.items = selected
print("eaten \(meal.name) \(meal.happiness) \(meal.items)")
if delegate == nil{
return
}
delegate!.add(meal)
if let navigation = self.navigationController{
navigation.popToRootViewControllerAnimated(true)
}
}
}