从AppDelegate调用委托功能不工作
问题描述:
我想调用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
}
答
您不能直接创建Viewcontroller
对象并设置app delegate
内delegate
。您需要先访问Viewcontroller
对象,因为它是内部的rootViewController
,所以你需要实现这样的
if let navigationController = window?.rootViewController, let
viewController = navigationController.childViewControllers.first as? ViewController {
viewController.delegate = self
}
答
你可以尝试从共享应用程序的AppDelegate实例。希望这将有助于
这是斯威夫特3
@IBAction func rotateAction(_ sender: UIButton) {
let delegate = UIApplication.shared.delegate as? AppDelegate
delegate?.callfromDelegte(indicator: indicator)
}
+0
谢谢你。 –
仍然无我更新code.Issue现在是,如果让它不往里走。 –
@TusharSharma,我可以看到代表的价值,它不是我的零 –
ViewController类你在故事板内定义了什么?它在Main.storyboard内吗? –