从appdelegate设置UIViewController委托

问题描述:

我想从我的应用程序委托设置视图控制器的委托。 但它不起作用。从appdelegate设置UIViewController委托

AppDelegate.m:

UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard" 
               bundle:nil]; 

SFLoginViewController * LoginVC = (SFLoginViewController *)[sb 
            instantiateViewControllerWithIdentifier:@"Login"]; 
LoginVC.delegate = self; 

SFLoginViewController.m

- (IBAction)Login:(id)sender { 

    NSLog(@"%@",self.delegate); //returns nil (!!) 

    //It should call the delegate method here 
    [[self delegate] LoginSucceeded]; 

} 

任何帮助吗?

+0

将自己添加为委托后,您是否将LoginVC添加到AppDelegate中的视图层次结构中?你在SFLoginVC.m中的哪个地方叫NSLog? – Greg

+0

@Greg你是什么意思查看hierach?我在UIbutton触发事件(这会触发登录过程)内调用它。 – mutex36

+0

也许你发布了更多的相关代码 – Merlevede

望着instantiateViewControllerWithIdentifierdocumentation ...

讨论您可以使用此方法来创建你想要操作和编程目前在 应用程序 视图控制器对象。在使用此方法检索控制器之前,必须使用Interface Builder中的适当标识符 字符串明确标记它。

此方法会在您每次调用指定的视图控制器 时创建一个新实例。

我不认为你在你的appDelegate有代码返回了通过故事板

+0

谢谢!我期待着这样的事情。我将使用@ hw731解决方案。 – mutex36

提出为什么不设置你的委托在ViewController中像这样的ViewController:

self.delegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate]; 

然后,您将能够处理AppDelegate中的委托事件。

通过这样做

(SFLoginViewController *)[SB instantiateViewControllerWithIdentifier:@ “登录”];

您正在创建SFLoginViewController的新实例。

我假设你已经有一个从故事板创建的这个viewcontroller的实例。 故事板中的实例是调用其方法登录名的实例:(id)发件人,而不是您为其分配的实例。

Try @ hw731 answer或者你需要将代表添加到从storyboard创建的实例(而不是你在appdelegate中创建的实例)。