Container View Controllers - notify parent of action

前端 未结 3 1779
北荒
北荒 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: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()
     }
    

提交回复
热议问题