On storyboards, views and passing data along

痴心易碎 提交于 2019-12-10 02:14:07

问题


In my Xcode 4.2 storyboard, i have 2 UIViewControllers, This one time and In band camp

  • In This one time, i have a UIButton with "silly name" on it
  • In In band camp, i have a UILabel with "label" on it

Considering that we're dealing with 2 separate classes AND we're in Xcode 4.2 using storyboards (where transition between views is setup via a segue) how can i pass "silly name" from view controller This one time to the label in view controller In band camp?"


回答1:


  1. Set the identifier of segue in storyboard to "AwesomeSegue"
  2. Implement prepareForSegue method
  3. Inside the method, check if identifier of segue matches "AwesomeSegue" - if yes, use the destinationViewControllerObject

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"AwesomeSegue"]) {
            InBandCampViewController *ibcVC = [segue destinationViewController];
            ibcVC.yourData = self.someStuff;
        }
    }
    



回答2:


I had to come up with one tweak for my code and also one alternative when used this solution.

In my case I had a Navigation Controller interrupting in the middle. MainViewController Segue was pointing to that Navigation Controller, then there was another Segue from it pointing to SecondViewController.

So if you'll ever need to get your ViewController from Navigation Controller, you could use such code:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // ScoreViewController Storyboard Segue
    if ([segue.identifier isEqualToString:@"AwesomeSegue"]) {

        // Finding ViewController that is needed in Navigation Controller
        UINavigationController *navigationController = segue.destinationViewController;
        ScoreViewController *scoreViewController = [[navigationController viewControllers] objectAtIndex:0];

        // Bellow implement your delegate or any data you want to pass
    }
}

Delegate:
scoreViewController.delegate = self;

Pass data:
scoreViewController.newLabel.text = self.oldLabel.text;

Call method:
[scoreViewController updateLabelText:self.oldLabel.text];

By the way, passing data you should assign it to the IBOutlet from the Sugue directly.
If you just pass NSString (or anything else), and will try to assign its text to the UILabel in viewDidLoad, it will be Nill.
It is because viewDidLoad is implemented before Segue.
Using viewDidAppear doesn't help here either, as it would load the text after SecondViewController is presented to the screen. You might see how UILabel text changes from "Label" to "silly name".

Well, if any one has some suggestions, I'm happy to hear, as I'm also just a newbie.



来源:https://stackoverflow.com/questions/7855888/on-storyboards-views-and-passing-data-along

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