gpt4 book ai didi

ios - 父 View Controller 如何通知它的 subview Controller 已删除自身?

转载 作者:IT王子 更新时间:2023-10-29 08:14:59 28 4
gpt4 key购买 nike

在 subview Controller 的实现中,通过以下代码删除 subview Controller :

- (void)commandFinishVC
{
[ self.view removeFromSuperview];
[ self removeFromParentViewController ];
}

subview Controller 及其 View 已成功删除,但如何通知父 View Controller ? -viewDidDisappear 未被调用并且 -viewDidUnload 已被弃用。

从我能找到的例子中,总是假设父 View Controller 是指定被删除的 child 的事件的发起者,但(对我来说) child 应该在其完成逻辑上是自主的。

是否应该使用 self.parentViewController 属性并在父 View Controller 中使用如下内容来调用 remove 方法?

- (void)commandFinishVC
{
[ childVC.view removeFromSuperview];
[ childVC removeFromParentViewController ];
}

最佳答案

是的,您的父 Controller 通常应该控制子 Controller 的添加和删除,因此您的第二种方法似乎更适用。查看Implementing a Container View Controller UIViewController 类引用部分。

我怀疑您可以摆脱以前的方法,即子项正在删除自身,但 Apple 在其文档和 WWDC 2011 session 上保持一致 Implementing UIViewController Containment说container controller负责管理children。

因此,对于您的 child 如何通知 parent 其已被移除的问题,目前还没有既定的协议(protocol)。但这并不奇怪,因为假定 parent 将启动此过程。就 child 需要启动此过程而言,文档建议 parent 应该有一个公共(public) API 来管理子 Controller 。

因此,虽然没有让子 Controller 通知父 Controller 的协议(protocol),但是有一个已发布的 API,父 Controller 可通过该 API 通知子 Controller 它们已被移动/移除。具体来说,当父 Controller 移除子 Controller 时,它应该调用 willMoveToParentViewController . This documentation明确表示我们必须执行此通知:

If you are implementing your own container view controller, it must call the willMoveToParentViewController: method of the child view controller before calling the removeFromParentViewController method...

因此,正如 Adding and Removing a Child 中所讨论的那样View Controller Programming Guide 的部分,在删除子项时,我们应该:

[childVC willMoveToParentViewController:nil];
[childVC.view removeFromSuperview];
[childVC removeFromParentViewController];

毫不奇怪,didMoveToParentViewController 的文档同样明确:添加子 Controller 时,必须在动画/转换(如果有)完成时调用 didMoveToParentViewController。我不知道如果我们不调用这两个通知方法会发生什么,但 Apple 说我们必须调用,因此这样做似乎是明智的。

关于ios - 父 View Controller 如何通知它的 subview Controller 已删除自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14166006/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com