Inserting rows to tableView using modal popup

我是研究僧i 提交于 2019-12-12 04:08:24

问题


I'm making a basic fitness app and within it I have a food diary that tracks the food you eat on a daily basis. I have a modal popup (picture below) that shows when you tap "add food". I'm having trouble inserting rows from the modal popup when the button "Save to Food Diary" is pressed. I'm also trying to update the calories label to the current calories the user accumulated throughout the day. Heres the code i have so far:

class PopupVC: UIViewController {
var section: Int?
var caloriesLabel = " "

var tableData: [String] = [""]
let foodDiary = FoodDiary()
var caloriesCell = caloriesForDiary()
@IBOutlet weak var foodTimeLabel: UILabel!
@IBOutlet weak var foodPopup2: UIView!
@IBOutlet weak var foodPopUp: UIView!
@IBOutlet weak var inputFood: UITextField!
@IBOutlet weak var inputCals: UITextField!

@IBAction func saveToDiary(_ sender: Any) {
    if (inputFood.text?.isEmpty)! || (inputCals.text?.isEmpty)! {
        return
    }

    caloriesLabel = foodDiary.testVariable
    tableData.append(inputFood.text!)
    foodDiary.tableView.beginUpdates()
    foodDiary.tableView.insertRows(at: [IndexPath.init(row: (tableData.count) - 1, section: section!)], with: .automatic)
    foodDiary.tableView.endUpdates()
    dismiss(animated: true, completion: nil)




}

Basically i'm trying to update my FoodDiaryVC using my PopUpVC, and i'm struggling to pass the data between both controllers to insertRows and to update my calories label. Hope this was explained well enough!


回答1:


The iOS approach would be to create a delegate.

@protocol AddRowDelegate {
func didAddRow(name : String, calories : String)
}

Then your FoodDiaryVC should implement it :

@class FoodDiaryVC : UIViewController, AddRowDelegate {
///Your code
}

Add a delegate variable to your PopUp Class

class PopUpVC : UIVIewController {

    weak var delegate : AddRowDelegate?
}

No you have to set the delegate when you show the Popup

myPopUp.delegate = self

When the user tap the "Add to diary", just call the delegate

delegate?.didAddRow(name: "blah", calories : "blah")



来源:https://stackoverflow.com/questions/43477084/inserting-rows-to-tableview-using-modal-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!