问题
I have a view controller with a collection view and when I click a cell, I pass a variable to another view controller, then push it onto the navigation stack.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("nextVC", sender: self.userArray[indexPath.row])
}
This is how I send the variable:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
let nextVC = segue.destinationViewController as! NextVC
if let senderId = sender!.objectForKey("uId") {
nextVC.userId = senderId as! String
}
}
This next view controller (nextVC) has a lot of stuff on it. I have done everything I can to optimize it but it still takes some time to load all the stuff. Is there a way I can prepare for segue, pass the variable, and let the next vc do it's thing, then when it's done loading, actually segue to it? (or show it)? I saw some other questions which talk about preloading view controllers but none of them dealt with passing a variable. This variable is very important because all the stuff in the nextVC has to know this one variable (based on cell touched) or it won't be able to load. I hope I explained this well enough, thanks for your time.
回答1:
If you access the view property of the destinationViewController, it will trigger the view to load. Since you don't really need the view, just assign it to _ to keep the compiler happy.
Try this:
if let senderId = sender!.objectForKey("uId") {
nextVC.userId = senderId as! String
_ = nextVC.view
}
This will trigger viewDidLoad to run before the segue happens. Make sure your code to set up your NextVC is in viewDidLoad and you should be good to go.
来源:https://stackoverflow.com/questions/40953609/how-can-i-pass-data-to-a-viewcontroller-and-load-it-before-pushing-it-onto-navig