【问题标题】:Delegation and childVIewController委托和 childVIewController
【发布时间】: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


    【解决方案1】:

    听起来您的委托建议很好,但它遗漏了通过情节提要构建视图控制器的参数。

    ChildViewController *controller = [[ChildViewController alloc]
            initWithNibName:@"ChildViewController"
                     bundle:[NSBundle mainBundle]];
    

    ...可以工作,但前提是项目中有一个名为“ChildViewController”的界面构建器文件。

    【讨论】:

    • 谢谢,我整天都在想这个。我已经尝试了你的建议,仍然没有爱。我实际上做了一个更简单的项目,如果你肯定没有更有趣的事情要做,如果你能快速浏览一下,我将不胜感激。如果这是我做的最后一件事,我会理解委派! stackoverflow.com/questions/34983566/…
    猜你喜欢
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2018-11-20
    相关资源
    最近更新 更多