1

我有一个 UIViewController 正在创建另一个视图控制器,并将其视图添加为子视图:

在父 UIViewController 中:

SlateMoreView* subView = [[SlateMoreView alloc] initWithNibName:@"SlateMoreView" bundle:nil];
[self.view addSubview:subView.view];

然后我需要在父视图中从子视图调用一个方法。

当我使用 [self.navigationController pushViewController: subView animated: YES] 添加子 UIViewController 时,我已经看到了如何执行此操作,因为我可以使用这种代码找到父级:

在子视图 UIViewController 中:

NSArray* viewControllerArray = [self.navigationController viewControllers]
int parentViewControllerIndex = [viewControllerArray count] - 2;
SlateView* slateView = [viewControllerArray objectAtIndex:parentViewControllerIndex];

...然后我可以向它发送消息。但是由于我使用 addSubView 手动添加了子视图,所以我不能这样做。

谁能想到我如何与我的父母 UIViewController 交谈?

谢谢!

4

3 回答 3

1

UIViews 有一个superview似乎是您正在寻找的属性。

UIViewController此外,除非您非常刻意构建自定义包含视图控制器,否则您可能不想像这样嵌套视图。见http://blog.carbonfive.com/2011/03/09/abusing-uiviewcontrollers/

于 2011-05-14T16:54:15.560 回答
0

您可能需要考虑是否可以通过使用 NSNotifications 来解决您的问题。当感兴趣的听众(您的超级视图)需要了解的事件发生时,您可以从您的子视图发布通知。当 superview 收到通知时,它可以运行您希望的任何代码。一直以来,子视图都不需要知道父视图。

这是减少类之间相互依赖的一种方法。

您也可以使用委托作为另一种选择。

于 2011-05-14T17:08:49.503 回答
0

当您将视图作为子视图添加到视图层次结构时,您将其放入响应者链中。您可以沿着响应者链向上到达视图控制器,因为它UIView由 a UIViewControllerhas UIViewControlleras its控制nextResponder

id object = theSubview;
do {
    object = [object nextResponder];
} while ( ![object isMemberOfClass:[YourViewController class]] );

// object has the view controller you need.
于 2011-05-14T18:32:22.147 回答