如何从子视图访问ParentViewController方法?

时间:2014-03-25 09:25:35

标签: ios objective-c uiview uiviewcontroller subview

我创建了一个调用UIViewController并将其作为subview加载的方法

cameraViewController = [[CameraViewController alloc] init];
        cameraViewController.view.frame = CGRectMake(0.0, 0.0, screenHeight, screenWidth);
        [cameraViewController drawCameraView:htmlProjID ProjectGUID:selectedProjGUID DoorGUID:cell.currentItem.doorGUID Info:nil doorName:cell.currentItem.doorDesc ViewName:@"Finishing"];
        [self.view addSubview:cameraViewController.view];

我想知道是否有一种简单的方法可以从原始camerViewController访问UIViewController(子视图)中的方法?

4 个答案:

答案 0 :(得分:5)

可能会返回您想要的内容:

 id mainViewController = [self.view.superview nextResponder];

Apple的文档 - [UIResponder nextResponder]:

UIView通过返回管理它的UIViewController对象(如果有的话)或超级视图(如果没有)来实现此方法

除此之外,你可以从here获得想法。

答案 1 :(得分:1)

根据此答案定义protocol并使用delegate ...

How do I create delegates in Objective-C?

答案 2 :(得分:1)

在这种情况下,NSNotification总是很方便。您只需在camerViewController的viewDidLoad中定义一个观察者:

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

然后您只需在原始视图中发布该名称的NSNotication:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"YourNSNotificaitionName" object:nil userInfo:Nil];

将在子视图上调用适当的方法。

答案 3 :(得分:0)

您可以从UIViewController访问Subview类的Public方法。但由于某些限制,它有时可能无效。

您可以使用Protocol来实现此类操作。为此,请遵循:

  • 声明要从中调用方法
  • 的ViewController的协议
  • 使用委托协议
  • 调用子视图的方法

执行它的其他方法是在AppDelegate文件中创建该方法&来自它的电话。

相关问题