Application Developer
Application Developer

Reputation: 105

Passing Data between ViewController in swift4

enter image description here

In this above Picture Two views are there. Top one is a view for showing date(for this view the class name is calender view) . And the bottom one is a tableview.the current view name is Main View When i am clicking on the cell of the tableview then it will go to the next view. When i am dismising the next view i want to pass some data to the calender view.How to achive this.

class MainView: UIViewController, UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let next = self.storyboard?.instantiateViewController(withIdentifier: "NextVC") as! NextVC
        self.present(next, animated: true, completion: nil)

    }

}


class NextVC: UIViewController {

    var sendingData: String?

    @IBAction func backAction(_ sender: Any) {
        dismiss(animated: true, completion: nil)

    }
}


class CalenderView: UIViewController{

    var receiveValue: String?
}

Here i want when i am dismissing the nextview the value of sendingData will pass to calender view.

How to do this ? Please help.

Upvotes: 1

Views: 77

Answers (1)

Vlad  Krupenko
Vlad Krupenko

Reputation: 360

I can give you two solutions:

  1. You can create your on custom notification.

First of all on back action you should post your notification with sendingData.

NotificationCenter.default.post(name: NSNotification.Name(rawValue: UpdateCalendarNotification), object: sendingData)

Next, on main view controller with calendar view you should register notification for "UpdateCalendarNotification" name.

    func registerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(updateCalendarView(_:)),
                                               name: NSNotification.Name(rawValue: "UpdateCalendarNotification"),
                                               object: nil)
    }

And on selector updateCalendarView(_:) you should handle changes for calendar view.

    @objc
    func updateCalendarView(_ notification: NSNotification) {
        if let sendingData = notification.object as? String {
            /// Update calendar view
        }
    }
  1. Second solution is public block for you "next controller".

On next view controller you should add this handler:

    var onDismiss: ((String?) -> Void)?

and in backAction method you should pass your data

    onDismiss?(sendingData)

In your main view controller you should implement this block like this:

let next = self.storyboard?.instantiateViewController(withIdentifier: "NextVC") as! NextVC
next.onDismiss = { [weak self] (sendingData) in
    self?.calendarView.receiveValue = sendingData
}
self.present(next, animated: true, completion: nil)

I hope this will help you)

Upvotes: 2

Related Questions