[英]Calling delegate function from AppDelegate not working
我正在嘗試在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.
}
}
委托始終為零,它永遠不會進入函數內部。 我現在不了解代表什么? 如何從控制器類的AppDelegate內部調用Google GIDSignInDelegate及其委托函數? 我知道這可能是一個非常愚蠢的問題,但我仍然想知道。
好的,因為我還沒有將我的控制器嵌入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
直接對象,並設置delegate
你的內部app delegate
。 您需要首先訪問Viewcontroller
對象,因為它位於rootViewController
內部,因此您需要像這樣實現
if let navigationController = window?.rootViewController, let
viewController = navigationController.childViewControllers.first as? ViewController {
viewController.delegate = self
}
您可以嘗試從共享應用程序獲取AppDelegate實例。 希望對你有幫助
這是Swift 3
@IBAction func rotateAction(_ sender: UIButton) {
let delegate = UIApplication.shared.delegate as? AppDelegate
delegate?.callfromDelegte(indicator: indicator)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.