【问题标题】:How to access ParentViewController method from subview?如何从子视图访问 ParentViewController 方法?
【发布时间】:2014-03-25 09:25:35
【问题描述】:

我创建了一个调用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];

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

【问题讨论】:

    标签: ios objective-c uiview uiviewcontroller subview


    【解决方案1】:

    这可能会返回你想要得到的东西:

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

    Apple 的 -[UIResponder nextResponder] 文档:

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

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

    【讨论】:

    • 感谢这完美的工作。要去阅读 nextResponder 我一直在使用委托做一些工作......我非常讨厌委托
    【解决方案2】:

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

    How do I create delegates in Objective-C?

    【讨论】:

      【解决方案3】:

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

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

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

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

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

      【讨论】:

        【解决方案4】:

        您可以从UIViewController 访问子视图类的公共方法。但由于某些限制,它有时可能无法正常工作。

        您可以使用协议来实现这些事情。为此,请遵循以下内容:

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

        执行它的其他方法是将该方法创建到 AppDelegate 文件中并从中调用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-05
          • 1970-01-01
          • 1970-01-01
          • 2012-02-27
          • 2013-05-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多