简体   繁体   中英

How to go back to previous view controller?

I have an UIViewController A with push segue to UIViewController B, in some case i need to repeat this for example:

ViewController A -> ViewController B -> ViewController A -> ViewController B

Also i need to pass data from ViewController B -> ViewController A

I don't want to create 4 ViewControllers, so how can I recycle code in this case?

You simple push and pop the same view controllers.

If you want B to communicate with A then setup a protocol at A that communitactes with the B. (or who ever implements the protocol)

B code

@protocol MyProtocol <NSObject>
-(void)callFromB:(id)data;
@end
@property (weak) id <MyProtocol> delegate;

implementation:

if ([self.delegate respondsToSelector:@selector(callFromB:)]){
        [self.delegate callFromB:data];
    }

A code

B.delegate = self;
-(void)callFromB:(id)data {
...
}

You should not recycle them. By that I mean you should not recycle the concrete instances of those view controllers. Certainly there might her some technical implementation allowing that but it is (contrary to table view cells) not necessary.

You are trying to optimise prematurely. Just create new view controller instances as you need. Any iPhone supporting iOS6 and later will handle that without any problem.

Passing the data can be done by a convenient method for example

-(void)configureWithData:(WhateverDataType *)paramData

In prepare for segue, you would obtain a reference to the target view controller and pass the data like this:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    CustomViewController *nextViewController = [segue destinationViewController];
    [nextViewController configureWithData:someData];
}

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