gpt4 book ai didi

iphone - 从子 UIViewController 到父 UIViewController 的通信

转载 作者:行者123 更新时间:2023-12-03 19:04:01 25 4
gpt4 key购买 nike

我还没弄清楚:我有一个 mainViewController 可以切换两个 View ,viewControllerA 和 ViewControllerB。我切换 View 的方法是在 mainViewController 中有一个 UIButton (mainButton),然后单击它切换 viewControllerA <--> ViewControllerB。

现在这是我的问题。我的 ViewControllerA 有一个 UIButton (ButtonA)。我希望通过单击它,它告诉 mainViewController 切换到另一个 View (viewControllerB)

换句话说, subview (viewControllerA)应该向mainViewController(其父 View )发送一条消息,表明它想要触发属于主视图而不是其自身(viewA)的方法。

请问我怎样才能实现这一目标?

最佳答案

与父对象通信时,您有几种设计模式可供选择。委派和通知都是不错的选择。

这里的重要思想是松散耦合的通信。通知使用单例来处理通信,而委派使用对父对象的弱引用。 (查看 cocoa 与爱:retain cycles)

如果您选择委派,您可以为 ViewControllerA 创建一个 MainViewController 必须遵守的非正式协议(protocol)。

您可以将其称为 ViewControllerADelegate 协议(protocol):

    @protocol ViewControllerADelegate

@optional
- (void)bringSubViewControllerToFront:(UIViewController*)aController;

@end

或者ViewControllerA可以发布通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyFunkyViewSwitcherooNotification" object:self];

如果 MainViewController 想知道的话,它应该监听:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swapThoseViews:) name:@"MyFunkyViewSwitcherooNotification" object:nil];

关于iphone - 从子 UIViewController 到父 UIViewController 的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1258169/

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