gpt4 book ai didi

ios - 容器 View Controller 与 childViewControllers 的通信

转载 作者:行者123 更新时间:2023-11-28 18:13:31 24 4
gpt4 key购买 nike

我有一个带有 3 个子 UIViewController 子类的容器 View Controller (使用 addChildViewController 添加)。我希望我的一个 subview Controller 在从我的容器 View Controller 上掉落某些东西时做一些事情。我无法理解这种沟通应该如何进行。如果我尝试创建一个委托(delegate),我会在我的 subview Controller 中收到一个错误,因为我将两个子类相互导入。

最佳答案

听起来您在编译您的应用程序时遇到了问题,因为相互 .h 文件导入,对吧?

Edit: upon reading your question again, I'm not 100% clear on which view controller needs to call which other one. If I mixed up the roles of parent and child view controller in my solution, just switch them. The techniques below let you communicate between any two view controllers (parent and child, sibling and sibling, etc.)

有很多方法可以处理这个问题。如果您想继续使用 delegate 模式,您可以简单地重写 header 以避免 .h 文件之一中的 #import:

ParentViewController.h:

#import "ChildViewController.h"

@interface ParentViewController: UIViewController {
@private
ChildViewController* childVc;
}

- (void) doSomething;

ChildViewController.h

@class ParentViewController;   // NOT #import!

@interface ChildViewController: UIViewController {
@private
ParentViewController* parentVc;
}

ChildViewController.m

#import "ParentViewController.h"

这应该避免使您的应用无法编译的循环依赖。

现在,尽管上述方法可行,但为了清洁起见,我可能会选择其他解决方案。使用协议(protocol)。 parent 可以实现协议(protocol),然后 child 只需要有一个实现协议(protocol)的委托(delegate):

#import "MyProtocol.h"

@interface ParentViewController: UIViewController<MyProtocol> {

}

- (void) doSomething;

在 MyProtocol.h 中:

@protocol MyProtocol
- (void) doSomething;
@end

然后在ChildViewController.h中

#import "MyProtocol.h"

@interface ChildViewController: UIViewController {
@private
id<MyProtocol> delegate;
}

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

在 ChildViewController.m 中:

   [delegate doSomething];

或者,您可以完全避免使用委托(delegate),并且 communicate between the controllers using NSNotificationCenter ,这将它们分离了一点,并避免了你的编译器循环(双向依赖)。

Here are the Apple docs on NSNotificationCenter

关于ios - 容器 View Controller 与 childViewControllers 的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825753/

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