简体   繁体   中英

Pass data from one view controller to another without transitioning

I have View Controller A (VCA) and View Controller B (VCB). VCA pulls data from an API call and fills in labels, etc. with the returned data.

When this data is retrieved I want to be able to pass some of it to VCB without transitioning to VCB. When it's time to "go" to VCB I want the data to already be there.

Currently I have the two view controllers linked via presenting and presented modal views. This works fine, when I present VCB I send along the data from VCA. However, from a UI/UX perspective, I am switching to a sliding panel view. So you start from VCA and then can swipe left to slide in VCB from the right.

Because of the sliding you can see both view controllers at the same time and so that's why I want VCB to already be complete visually.

My current code in VCA is called on a doubleTap gesture recognizer:

- (void)showDetailView
{
    // Initialize VCB
    ViewContollerB *vcb = [[ViewContollerB alloc] init];

    //  ················································
    //  Pass data to ViewContollerB
    //  ················································

    vcb.currently = currently;
    vcb.hourly    = hourly;
    vcb.daily     = daily;
    vcb.unitTemp  = unitTemp;

    vcb.currentLocationCity   = currentLocationCity;
    vcb.currentLocationRegion = currentLocationRegion;
    vcb.currentTemp           = currentTemp;

    // Set transition style to cross fade
    vcb.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    // Present the daily details
    [self presentViewController:vcb animated:YES completion:nil];
}

Like I said before, this works fine.

On the receiving end (VCB), I have things like this in - (void)viewWillAppear:(BOOL)animated

if (currentTemp) {
    // Displays data from passed variables
    [self displayHeaderInfo];
}

What I would like to do is essentially this in VCA:

// PRETEND DATA RETURNED FROM API CALL IN VCA

if (currentTemp) {
    // Set array for VCB
    vcb.currentTemp = currentTemp;

    **** CODE TO SEND THIS TO VCB ****
    **** BUT NOT GO TO VCB, STAY  ****
    **** RIGHT HERE IN VCA.       ****

    // Display in VCA
    [self displayCurrentTemp];
}

Is this possible?

In this case, it's best if you assign the role of fetching the data to a separate DataFetcher object. Don't make your UIViewControllers responsible for fetching the data.

Implement a DataFetcherDelegate or a completion block that will notify the ViewControllers when the data has been fetched.

See this answer for an example implementation of the delegate approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM