objective-c - 从 subview Controller 传回数据

标签 objective-c uicontainerview childviewcontroller parentviewcontroller

我是初学者,我有一个项目,需要从 subview Controller 传回数据。具体来说,我的容器中有一个选择器 View ,我希望能够使用它来选择一个选项(比如简化为从十种颜色的数组中选择一种颜色)。然后我希望能够访问我的父 View Controller 中选择的颜色并用它做一些事情。我已经研究了几天了,在 S.O. 的一个相关问题中找到了最接近我正在寻找的答案。这是:

“关于将值传递给containerView Controller ,您可以在ChildViewController中创建一个您想要传递的值的属性。然后在ParentViewController中执行如下操作:

self.ChildViewController.yourProperty = yourValue

相反可以通过 4 种方式完成:

您可以制定委托(delegate)协议(protocol)来在 Controller 之间传递数据。

您可以在 ChildViewController 中发布通知并将父 Controller 添加为观察者。

您可以使用 KVO。

最简单的方法是,您可以在parentviewController中创建一个属性并按如下方式访问它:“

((YourParentViewControllerClassType *)self.parentViewController).yourParentProperty = TheValueYouWant;

现在,我想首先尝试第四个选项,因为委托(delegate)、kvo 等是我已经阅读过但尚未准备好解决的选项。我需要帮助的是最后一个选择。

假设我的 subview Controller 中有一个属性,用于存储所选颜色。像这样的东西:

@interface ViewController ()

@property NSString *ChosenColorInChildVC;

@end

然后,稍后:

self.ChosenColorInChildVC = [self pickerView:myPickerView titleForRow:[myPickerView selectedRowInComponent:1] forComponent:1]];

我将如何使用建议传递该值:

((YourParentViewControllerClassType *)self.parentViewController).yourParentProperty = TheValueYouWant;

有人可以帮我简化一下吗?谢谢

最佳答案

我将通过一个示例向您解释委托(delegate)的工作原理。

像这样编辑你的 ChildViewController.h :

@protocol ChildViewControllerDelegate; 

@interface ChildViewController : UIViewController

@property (weak)id <ChildViewControllerDelegate> delegate;

@end

@protocol ChildViewControllerDelegate <NSObject > 

- (void) passValue:(UIColor *) theValue;

@end

在 ChildViewController.m 上,当您想将某些内容传递回 ParentViewController 时,请执行以下操作:

 - (void) myMethod
 {
   [delegate passValue:[UIColor redColor]]; // you pass the value here
 }

在您的 ParentViewController.h 上

#import "ChildViewController.h"

@interface ParentViewController : UIViewController <ChildViewControllerDelegate >  // you adopt the protocol
{
}

在您的 ParentViewController.m 上:

- (void) passValue:(UIColor *) theValue
   {
      //here you receive the color passed from ChildViewController
   }

现在要小心了。仅当您设置委托(delegate)时,一切才会起作用。 因此,当您在 ParentViewController 类中声明 ChildViewController 时,请执行以下操作:

ChildViewController * controller = [[ChildViewController alloc]initWithiNibName:@"ChildViewController"];
controller.delegate = self; //without this line the code won't work!

关于objective-c - 从 subview Controller 传回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34969152/

相关文章:

ios - AssetLibrary - 如何加载方向校正?

ios - 如何在 iOS 8 的全屏模式下在 UIWebView Player 中接收通知?

ios - "Message sent to deallocated instance"错误

uitableview - TableViewController 的 ContainerView 不起作用?

iOS - 如何从容器 View 访问变量并将其传递回 View Controller

ios - 在 iOS 中,使用 Storyboard,如何在容器 View 中设置 View Controller ?

objective-c - Objective-C 中的 block 变量

ios - 在容器 View 中,导航 Controller 的导航栏未调整大小以包含状态栏

iOS 访问parentViewController 中的属性

ios - subview Controller 在呈现和关闭模态视图后失去委托(delegate)