how to pass data between these two view controllers in swift

↘锁芯ラ 提交于 2019-12-13 08:59:35

问题


in this case i have tabbar controller and navigation controller between the two VC,which means firstly i want to pass data between the first VC and the tabbar controller, and secondly i want to pass the same data from the tab bar controller to navigation controller , and finnally to the last VC,i searched for example in the net but i didn't find anything useful.


please can u help me pass data between these two viewcontrollers ,any example will be great, thaank's.


回答1:


Set an identifier to the segue in your storyboard (click on the segue and then on the right menu go to attributes inspector) and then you probably need to click on the cell to make the segue in didSelectRowAt, do this in there:

self.performSegue(withIdentifier: "YOUR IDENTIFIER", sender: DATA TO PASS or nil)

And then create the segue function

override func prepare(for segue: UIStoryboardSegue, sender: Any!){
    if (segue.identifier == "YOUR IDENTIFIER") // good to have if you have multiple segues
    {
        let secondVC = segue.destination as! SecondViewController
        secondVC.str = "DATA" // now you can access public variables and functions from the second viewController
    }
}



回答2:


you can use the @Rashwan L answer, and pass the infobetween all controllers until the last, or simply create a variable in the AppDelegate and use it when the desired controller arrives.

var App: AppDelegate {
    return (UIApplication.sharedApplication().delegate as! AppDelegate)
}

App.myVar = "My DATA"

and when use you can get with App.myVar




回答3:


I have been trying to figure this out for a while. Currently, I create a property to hold the data that I want to pass, right before I call performSelector:, then use that property to pass the data into the appropriate view controller in prepareForSegue:. After its used, I nil out the data. Looks like this

@property (...) NSString *selectedString;

- (void)methodThatPicksTheData {
  self.selectedString = @"someString";
  [self performSegue:kSegueIdentifier];
}

- (void)prepareForSegue:(SegueClassWhoseNameICannotRememberRightNow)segue {

  if ([segue.identifier isEqualToString:kSegueIdentifier]) {
     CustomViewController *vc = segue.destinationViewController;
     vc.string = self.selectedString;
     self.selectedString = nil;
  }

}

its not perfect, but it provides a way to clearly designate what data needs to get passed.



来源:https://stackoverflow.com/questions/39921558/how-to-pass-data-between-these-two-view-controllers-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!