I have a view controller. That does a Modal present Segue
of a full screen view controller. It passes the image data list to the full screen view controller. This list has properties associated with it such as likes, views, etc. I have looked at ther answers, but believe they will completely replace the current array, which I think will completely reload every bit of data that is cashed on the first view. So I only want to modify data that needs to be modified.
Class FirstController {
var photosList: [customStruct] = [Photo1,Photo2,Photo3]
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "photofull" {
if let fullImaageViewController = segue.destination as? ImageDetailViewController {
fullImageViewController.photosList = photosList
}
}
}
here the data is passed forward through a Modal view controller. In the full imageViewcontroller, the data, such as like can be altered. [photosList[1].imageLikes = photosList[1].imageLikes+1
The only problem I am only able to change this data on the fullImageViewController, not in the FirstController. is there a way to access it on the previous one too?
I would like to do something like FirstController().[photosList[1].imageLikes = FirstController.photosList[1].imageLikes+1
which doesn't work.
Well, what you need here is a simple delegate protocol to transfer data from one ViewController
to another ViewController
.
Below are the steps how to work with protocol.
In ViewController2
or fullImaageViewController
do the following steps.
Just above your class declaration declare your delegate.
protocol MyDelegate:class { // declare your protocol a class protocol
func sendDataBack(value: Photo)
}
In class
declare a variable
of your delegate
weak var myDelegateObj: MyDelegate? // always declare a weak delegate so that it cannot capture the memory of the object
and when you dismiss the VC
just call the delegate with line
myDelegateObj?.sendDataBack(value: Photo)
Now go to your FirstViewController
and go to the line where you have declared the FirstViewController Obj
if not declare it either in viewdidload
or when you presenting
your view.
and do the following.
let vc = FirstViewController()
vc.myDelegateObj = self
and implement the method your delegate in the FirstViewController
In FirstViewController:
make your firstView conform to MyDelegate Protocol by doing:
class FirstViewController: UIViewController,MyDelegate
and Implement the MyDelegate Method
// update only altered photo
func sendDataBack(value: Photo) {
if let index = photosList.index(where: {$0.imageID == Photo.imageID}){
PhotoList[index] = Photo
}
}
And then before the initial segue, I use
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "photofull" {
if let fullImaageViewController = segue.destination as? ViewController2 {
fullImaageViewController.myDelegateObj = self
}
}
}
Hope this helps.