Container View Controllers - notify parent of action

前端 未结 3 1761
北荒
北荒 2020-12-28 11:24

Say I have a custom container view controller (MainViewController) where I do something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];        

           


        
相关标签:
3条回答
  • 2020-12-28 12:01

    There's another way too... Every view controller has a parentViewController property so using that you can do this...

    In MainViewController define a method for the action you want to perform...

    - (void)someMethod:(BOOL)someParam;
    

    Then in HomeViewController you can do...

    MainViewController* parent = (MainViewController*)[self parentViewController];
    [parent someMethod:paramValue];
    

    HTH :)

    0 讨论(0)
  • 2020-12-28 12:06

    You can either use delegate or block;

    Using delegate

    Create a protocol :

    @protocol SomeProtocol <NSObject>
    - (void)someAction; 
    @end 
    

    Just declare a delegate in HomeViewController.h like this:

    id<SomeProtocol> delegate; 
    

    and then in MainViewController's viewDidLoad set it like this:

    homeVC.delegate = self;
    //some where in MainViewController implement the protocol method
    -(void)someAction
    {
        //do something
    }
    

    then when you press the button in homeVC, just simply call:

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

    Using Block:

    In HomeViewController.h declare a block property:

    typedef void (^ActionBlock)();
    
    @property (nonatomic, copy) ActionBlock block;
    

    then in MainViewController ViewDidLoad:

    homeVC.block = ^(){
        //do something
    };
    

    then when you press the button in homeVC, just simply call:

    self.block();
    
    0 讨论(0)
  • 2020-12-28 12:11

    This is a very common pattern. The parent will be the actual instance that will handle the action, by providing a protocol and a default extension.

    In Swift 3:

    Parent view controller:

    protocol SomeProtocol {
        func foo()
    }
    
    extension ParentViewController: SomeProtocol {
        func foo() {
            // Parent handles it
        }
    }
    

    Child view controller:

     @IBAction func tapGo(_ sender: Any) {
        (parent as? SomeProtocol)?.foo()
     }
    
    0 讨论(0)
提交回复
热议问题