【发布时间】:2016-05-01 03:18:04
【问题描述】:
这是一个关于委托的问题,试图从子视图控制器传回一些数据,该子视图控制器链接到具有选取器视图的容器视图。之前问过一个相关的问题,有人好心回复了如下代码:
“我将通过一个示例向您解释委托是如何工作的。
像这样编辑您的 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!"
无论如何,这对我帮助很大,是我得到的最有用的建议之一。不幸的是,这段代码中的一行代码返回了一个错误,并且使委托为零。就是这个:
ChildViewController * controller = [[ChildViewController alloc]initWithiNibName:@"ChildViewController"];
错误是:“'ChildViewController' 没有可见的@interface 声明选择器'initWithNibName:'
当我按照我正在尝试学习的东西的说明进行操作时,我有点迷茫。首先,当我尝试键入它时,建议的方法采用另一个参数: [[ChildViewController alloc]initWithNibName: bundle:];
我已经完成了一个 NSLog 来获取 [self.delegate 描述] 并且它返回为空。任何人都可以帮忙吗?谢谢
【问题讨论】:
标签: objective-c delegation childviewcontroller initwithnibname