How to send data from RightViewController to MainView Controller in Swift 4?

109 Views Asked by At

enter image description here

Hello, I am using MMDrawerController for right side menu. I have 2 ViewController First is HomeVC with Product Listing data in UICollectionView and there's 1 filter button.

When i press that filter button I push to filter screen RightViewVC. Now what I want is, I want to pass that selected filter values to HomeVC. How can I do this?

1

There are 1 best solutions below

3
On BEST ANSWER

You can do this by multiple way

1. By using Block Method

When you push to RightViewVC write below code.

let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "RightViewVC") as! RightViewVC
nextViewController.delegate = self as! customeDelegate
nextViewController.onApplyFilterTap = {(_ arrSelectedFilter: NSMutableArray) -> Void in
    self.collectionView.reloadData()
}
self.show(nextViewController, sender: self)

Define this in RightViewVC controller. I created array you can change it as per your requirement.

var onApplyFilterTap: ((_ arrSelectedFilter: NSMutableArray) -> Void)? = nil 

You need to call like this

self.arrFilterSelection.add(whichButtonClicked)
self.arrFilterSelection.add(locationTextView.text!)
self.arrFilterSelection.add(byPriceToTextField.text!)
self.arrFilterSelection.add(byPriceFromTextField.text!)
self.arrFilterSelection.add(timeTextview.text!)

onApplyFilterTap!(self.arrFilterSelection)

2. By using NotificationCenter

Write below in your HomeVC

NotificationCenter.default.addObserver(self, selector: #selector(refreshProductListBasedonSelectedFilterValue(_:)), name: NSNotification.Name(rawValue: "refreshProductListBasedonSelectedFilterValue"), object: nil)


@objc func refreshProductListBasedonSelectedFilterValue(_ notification: Notification) {
    let info = notification.object as? NSDictionary

    let arrSelectedFilteredValues = info?.value(forKey: "selectedFilter") as! NSMutableArray
    self.collectionView.reloadData()
}

From RightViewVC you need to call like this.

let dict = NSMutableDictionary()
dict.setValue(self.arrFilterSelection, forKey: "selectedFilter")
NotificationCenter.default.post(name: NSNotification.Name("refreshProductListBasedonSelectedFilterValue"), object: dict)

3. You can also use delegate