iOS: How to achieve behavior like Android's startActivityForResult

后端 未结 3 636
名媛妹妹
名媛妹妹 2021-02-07 10:04

I\'m an Android developer working on an iOS version of our app. I need to know how to achieve behavior similar to startActivityForResult on Android. I need to show a new view co

3条回答
  •  天涯浪人
    2021-02-07 10:20

    There are a couple ways, so mostly you do this yourself with various patterns. You can set up a navigation controller in the app delegate as follows:

    self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    self.navigationController = [[ UINavigationController alloc ] initWithRootViewController:self.viewController ];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    

    Then when you want to present a new vc you can do this:

    OtherViewController *ovc = [[ OtherViewController alloc ] initWithNibName:@"OtherViewController" bundle:nil ];
    [ self.navigationController pushViewController:ovc animated:YES ];
    

    To go back do this:

    [ self.navigationController popViewControllerAnimated:YES ];
    

    As far as a callback goes one way to do this is to make a protocol like this somewhere in your project:

    @protocol AbstractViewControllerDelegate 
    
    @required
    - (void)abstractViewControllerDone;
    
    @end
    

    Then make each view controller you want a callback to be triggered in a delegate aka:

     @interface OtherViewController : UIViewController 
    
     @property (nonatomic, assign) id delegate;
    
     @end
    

    Finally when you present a new vc assign it as a delegate:

      OtherViewController *ovc = [[ OtherViewController alloc ] initWithNibName:@"OtherViewController" bundle:nil ];
      ovc.delegate = self;
      [ self.navigationController pushViewController:ovc animated:YES ];
    

    then when you dismiss the ovc, make this call

     [self.delegate abstractViewControllerDone];
     [ self.navigationController popViewControllerAnimated:YES ];
    

    And in the rootVC, which conforms to the protocol you made, you just fill out this method:

     -(void) abstractViewControllerDone {
    
     }
    

    That you just made a call to. This requires a lot of setup but other options include looking into NSNotifications and blocks which can be simpler depending on what your doing.

提交回复
热议问题