OutOfOdds
OutOfOdds

Reputation: 13

How to reloadData() in ViewController #1 after ViewController #2 is dismissed?

i am new to iOS here is my question:

I have a saveCardViewController (Presented Modally) with some textFields and Save button.

@IBAction func Save(_ sender: UIButton) {
    
    date = datePicker.date
    
    try! realm.write() {
        
        sessionCard.pokerType = pokerTypeSegment.titleForSegment(at: pokerTypeSegment.selectedSegmentIndex)!
        date = dateFormatter.string(from: date)
        sessionCard.handsPlayed = Int(handPlayedTextlabel.text!) ?? 0
        sessionCard.moneyIn = Int(moneyInTextLabel.text!) ?? 0
        sessionCard.moneyOut = Int(moneyOutTextLabel.text!) ?? 0
        sessionCard.timePlayed = Int(timePlayedTextLabel.text!) ?? 0
        sessionCard.sortDate = date
        
        realm.add(sessionCard)
        
    }
    dismiss(animated: true, completion: nil)
}

How can I reloadData() on my main ViewController, after Save button is pressed and saveCardViewController is dismissed.

Thanks!

EDIT # 1:

Thank you @davidev for your answer,I made changes but still does not update

My ViewController With TableView:

class SessionViewController: BackgroundViewController, RefreshViewDelegate {


func refreshView() {
    tableView.reloadData()
}
    
override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView.delegate = self
    tableView.dataSource = self       

}

My ViewController with data and Save button:


    protocol RefreshViewDelegate {
    func refreshView()
}

class AddSessionViewController: UIViewController, UITextFieldDelegate {
    
    var delegate: RefreshViewDelegate?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
               
        
    }

 @IBAction func TEST2(_ sender: UIButton) {
        
        delegate?.refreshView()
        dismiss(animated: true, completion: nil)
        
    }

Upvotes: 1

Views: 68

Answers (1)

davidev
davidev

Reputation: 8517

You can use delegate pattern to achieve this.

Declare your Refresh Protocol like this:

protocol RefreshViewDelegate {
    func refreshView()
}

Make your parent view conform to this protocol and implement refreshView() with your custom refresh action. Also make sure to set the delegate of the child view to self.

Inside saveCardViewController declare your delegate variable

var delegate : RefreshViewDelegate?

And call the delegate action inside your IBaction

delegate?.refreshView()

Edit:

I just saw your updated code. As you are using Storyboard segues, you still have to set the delegate via code. In your main view controller add the function:

override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
    if let viewController = segue.destinationViewController as? AddSessionViewController
    {
        viewController.delegate = self
    }
}

Upvotes: 1

Related Questions