2017-08-06 56 views
0

我想調用AppDelegate中的委託功能,但似乎它永遠不會被調用。從AppDelegate調用委託功能不工作

import UIKit 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate,appdelegate { 

    var window: UIWindow? 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     if let navigationController = window?.rootViewController, let 
      viewController = navigationController.childViewControllers.first as? ViewController { 
      viewController.delegate = self 
     } 
     // Override point for customization after application launch. 
     return true 
    } 

    func callfromDelegte(indicator: UIActivityIndicatorView) { 
     indicator.stopAnimating() 
    } 

ViewController-:

import UIKit 

protocol appdelegate:class { 
    func callfromDelegte(indicator:UIActivityIndicatorView) 
} 
class ViewController: UIViewController { 

    @IBOutlet weak var indicator: UIActivityIndicatorView! 
    weak var delegate:appdelegate? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     indicator.startAnimating() 
     indicator.hidesWhenStopped = true 
    } 

    @IBAction func rotateAction(_ sender: UIButton) { 
     if delegate != nil{ 
     delegate?.callfromDelegte(indicator: indicator) 
     } 
    } 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

代表始終是零,它永遠不會走了進去功能。那麼我現在不是 關於代表呢? Google GIDSignInDelegate及其委託函數如何從控制器類的AppDelegate中調用?我知道這可能是非常愚蠢的問題,但我仍然想知道。謝謝

好吧,因爲我沒有用navigationController嵌入我的控制器。因此,如果讓,它不會進入。它的工作只是喜歡這個 - :

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
//  if let navigationController = window?.rootViewController, let 
//   viewController = navigationController.childViewControllers.first as? ViewController { 
//   viewController.delegate = self 
//  } 
     // Override point for customization after application launch. 

     let controller = window?.rootViewController as! ViewController 
     controller.delegate = self 
     return true 
    } 

回答

1

您不能直接創建Viewcontroller對象並設置app delegatedelegate。您需要先訪問Viewcontroller對象,因爲它是內部的rootViewController,所以你需要實現這樣的

if let navigationController = window?.rootViewController, let 
    viewController = navigationController.childViewControllers.first as? ViewController { 
viewController.delegate = self 
} 
+0

仍然無我更新code.Issue現在是,如果讓它不往裏走。 –

+0

@TusharSharma,我可以看到代表的價值,它不是我的零 –

+0

ViewController類你在故事板內定義了什麼?它在Main.storyboard內嗎? –

1

你可以嘗試從共享應用程序的AppDelegate實例。希望這將有助於

這是斯威夫特3

@IBAction func rotateAction(_ sender: UIButton) { 
     let delegate = UIApplication.shared.delegate as? AppDelegate 

     delegate?.callfromDelegte(indicator: indicator) 
} 
+0

謝謝你。 –