http://imagizer.imageshack.us/a/img921/5386/WxStTe.png
http://imagizer.imageshack.us/a/img924/7412/4ubZnJ.png
Código do ViewContoller
import UIKit
protocol AddMealDelegate{
func add(meal:Meal)
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var nameField: UITextField?
@IBOutlet var happinessField: UITextField?
var delegate:AddMealDelegate?
var items = [
Item(name: "Eggplant Brownie", calories: 10),
Item(name: "Zuccchini muffin", calories: 90),
Item(name: "Salsicha", calories: 15),
Item(name: "Pizza", calories: 100),
Item(name: "Lazanha", calories: 800),
]
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> 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, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if cell == nil {
return
}
cell!.accessoryType = UITableViewCellAccessoryType.checkmark
}
@IBAction func add() {
if nameField == nil || happinessField == nil{
return
}
let name:String = nameField!.text!
let happiness:Int = Int(happinessField!.text!)!
let meal = Meal(name: name,happiness: happiness)
print("eaten: \(meal.name) \(meal.happiness)!")
if (delegate == nil){
return
}
delegate!.add(meal: meal)
if let navigation = self.navigationController{
navigation.popViewController(animated: true)
}
}
}
Código MealsTableViewController
import UIKit
class MealsTableViewController: UITableViewController, AddMealDelegate {
var meals = [Meal(name: "eggplant-brownie", happiness: 5),
Meal(name: "zucchini muffin", happiness: 3)
]
func add(meal: Meal) {
meals.append(meal)
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "addMeal") {
let view = segue.destination as! ViewController
view.delegate = self
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let meal = meals[ row ]
let cell = UITableViewCell(style: UITableViewCellStyle.default,
reuseIdentifier: nil)
cell.textLabel?.text = meal.name
return cell
}
}