从 AppDelegate 调用委托函数不起作用
Posted
技术标签:
【中文标题】从 AppDelegate 调用委托函数不起作用【英文标题】:Calling delegate function from AppDelegate not working 【发布时间】:2017-08-06 16:36:13 【问题描述】:我正在尝试在 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.
Delegate 总是 nil,它永远不会进入函数内部。什么是我不 现在谈代表了吗? Google GIDSignInDelegate 及其委托函数如何在 AppDelegate 中从控制器类调用?我知道这可能是一个非常愚蠢的问题,但我仍然想知道。谢谢
好的,因为我没有用 navigationController 嵌入我的控制器。所以它不会进入 if let。它就像这样工作-:
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
对象并将delegate
设置在您的app delegate
中。您需要先访问Viewcontroller
对象,因为它在rootViewController
内部,因此您需要像这样实现
if let navigationController = window?.rootViewController, let
viewController = navigationController.childViewControllers.first as? ViewController
viewController.delegate = self
【讨论】:
仍然没有我更新了代码。现在的问题是如果让它不会进入内部。 @TusharSharma,我可以看到委托值,它对我来说不是零 ViewController 类是你在故事板中定义的?它在 Main.storyboard 里面吗? 您也可以尝试 Woof 方法。如果您不想制作 customdelegate。 你说得对,我需要访问控制器。不过我没有使用导航控制器。【参考方案2】:您可以尝试从共享应用程序中获取 AppDelegate 实例。希望对你有帮助
这是 Swift 3
@IBAction func rotateAction(_ sender: UIButton)
let delegate = UIApplication.shared.delegate as? AppDelegate
delegate?.callfromDelegte(indicator: indicator)
【讨论】:
以上是关于从 AppDelegate 调用委托函数不起作用的主要内容,如果未能解决你的问题,请参考以下文章
从 App Delegate 调用时,PushViewController 不起作用