2

我是初学者,我有一个项目需要从 childviewcontroller 传回数据。具体来说,我的容器中有一个选择器视图,我希望能够使用它来选择一个选项(比如简化从十种颜色的数组中选择的一种颜色)。然后我希望能够访问我的父视图控制器中选择的颜色并用它做一些事情。我已经对此进行了几天的研究,并且在关于 SO 的相关问题中找到了与我正在寻找的内容最接近的答案,它是:

“关于将值传递给 containerView 控制器,您可以在 ChildViewController 中为您希望传递的值创建一个属性。然后在您的 ParentViewController 中执行以下操作:

self.ChildViewController.yourProperty = yourValue

可以通过 4 种方式进行相反的操作:

您可以创建一个委托协议来在您的控制器之间传递数据。

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

您可以使用 KVO。

最简单的方法是,你可以在你的 parentviewController 中创建一个属性并像下面这样访问它:"

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

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

假设我的子视图控制器中有一个属性,用于存储所选颜色。就像是:

@interface ViewController ()

@property NSString *ChosenColorInChildVC;

@end

然后,稍后:

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

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

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

有人可以为我进一步降低它吗?谢谢

4

3 回答 3

5

我将通过一个示例向您解释委托是如何工作的。

像这样编辑您的 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
   }

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

ChildViewController * controller = [[ChildViewController alloc]initWithiNibName:@"ChildViewController"];
controller.delegate = self; //without this line the code won't work!
于 2016-01-23T22:29:01.997 回答
0

@metronic 是对的;使用委托。

通常你也会在你的委托方法中包含发送者:

-(void) childViewController:(ChildViewController*)viewController passValue:(UIColor*) theValue 
于 2016-01-23T22:44:45.337 回答
0

注意:这是非常重要的。

在#import 行上方编写协议声明代码,例如

@协议 - - -

@结尾

进口 - -

@interface 类名 ---

于 2017-10-29T06:56:06.940 回答