ContainerViewController 委托给 ChildViewController

ContainerViewController delegate to ChildViewController

ContainerViewController 将方法 -delegateMethod 委托给 ChildViewController.
但是在下面的代码中,没有调用-delegateMethod
我想是因为 _childViewController 已经发布了。
我该如何修复才能使 运行 -delegateMethod?

ContainerViewController.h

@protocol ContainerViewDelegate <NSObject>

- (void)delegateMethod;

@end

@interface ContainerViewController : UIViewController

@property (nonatomic, assign) id<ContainerViewDelegate> delegate;

@end

ContainerViewController.m

@interface ContainerViewController () {
    ChildViewController *_childViewController;
}

//...

- (void)viewDidLoad
{
    _childViewController = [[WeeklyViewController alloc]init];
    [self addChildViewController:_childViewController];
    [self.view addSubview:_childViewController.view];
    [_childViewController didMoveToParentViewController:self];
}

- (void)buttonAction {
    [self.delegate delegateMethod];
}

ChildViewController.m

@interface ChildViewController () <ContainerViewDelegate>

//...

- (void)delegateMethod {
    NSLog(@"succeed!");
}

您从未设置委托,因此 self.delegate 将为零。你应该这样做,

    - (void)viewDidLoad
{
    _childViewController = [[WeeklyViewController alloc]init];
    self.delegate = _childViewController;
    [self addChildViewController:_childViewController];
    [self.view addSubview:_childViewController.view];
    [_childViewController didMoveToParentViewController:self];
}