问题
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