2014-03-06 83 views
3

我想從我的應用程序委託設置視圖控制器的委託。 但它不起作用。從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

回答

2

望着instantiateViewControllerWithIdentifierdocumentation ...

討論您可以使用此方法來創建你想要操作和編程目前在 應用程序 視圖控制器對象。在使用此方法檢索控制器之前,必須使用Interface Builder中的適當標識符 字符串明確標記它。

此方法會在您每次調用指定的視圖控制器 時創建一個新實例。

我不認爲你在你的appDelegate有代碼返回了通過故事板

+0

謝謝!我期待着這樣的事情。我將使用@ hw731解決方案。 – mutex36

4

提出爲什麼不設置你的委託在ViewController中像這樣的ViewController:

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

然後,您將能夠處理AppDelegate中的委託事件。

0

通過這樣做

(SFLoginViewController *)[SB instantiateViewControllerWithIdentifier:@ 「登錄」];

您正在創建SFLoginViewController的新實例。

我假設你已經有一個從故事板創建的這個viewcontroller的實例。 故事板中的實例是調用其方法登錄名的實例:(id)發件人,而不是您爲其分配的實例。

Try @ hw731 answer或者你需要將代表添加到從storyboard創建的實例(而不是你在appdelegate中創建的實例)。