问题
So I want to be able to pass a variable from one view to another view easily. I've seen ways by doing it via a Segue but I was hoping for something simpler than that if possible.
Is there any way to just transfer the content of one variable and save it in another view really easily. I am aware this might not be possible.
If this isn't possible, please could someone explain how to use the Segue method? I've seen various online tutorials explaining how to do it but they are all applying it to a situation. I just want to know the bare code and how it works then apply it to my own situation. So just basically a way to transfer a variable from one view to another that someone with very very little knowledge like me will understand. I understand terminology as I program in other languages but swift is very new to me.
I should add that the coding language I am using is swift.
I would appreciate it if someone could help me with this.
Thank you
回答1:
If it just one variable that you are sending, i would use prepare for segue.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "IdentifierOfSegueGoesHere"
{
if let destinationVC = segue.destinationViewController as? OtherViewController{
destinationVC.dictionary = self.dictionary
}
}
}
If you are passing a lot of data, e.g. a list of friends etc then i would create a singleton class that stores them that can be accessed from anywhere.
If you are passing multiple variables that don't have enough of a connection to create a singleton class then you can put them into a dictionary and pass the dictionary.
回答2:
This is not a recommended approach. If you are not a computer science purist you can use global variables. This by-passes protections offered by the compilation process.
来源:https://stackoverflow.com/questions/29376806/how-can-i-pass-a-variable-from-one-view-to-another-easily