簡體   English   中英

如何從Swift中的appdelegate調用ViewController中的func?

[英]How to call the func in ViewController from appdelegate in Swift?

我試圖從Swift中的appdelegate調用ViewController的函數?

Appdelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var first: FirstViewController!

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {

        FirstViewController.fileurl(url)
        first.fileurl(url)
        return true
    }
}

FirstViewController.swift

import UIKit
class FirstViewController: UIViewController {
    var externalFile: NSURL!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func fileurl(url: NSURL){
        externalFile = url
        println("externalFile = \(externalFile)")
}
}

Appdelegate.swift ,我調用FirstViewController.fileurl()並嘗試調用first.fileurl()

當我調用FirstViewController.fileurl(url) ,它顯示無法使用類型為'(NSURL)'的參數列表調用'fileurl'

當我調用first.fileurl(url) ,它崩潰並且錯誤日志是致命錯誤:在展開Optional值時意外地發現nil

我錯過了什么嗎? 提前致謝。

這是你的UIViewController first調用,沒有初始化。 如果這在另一個地方完成,例如在加載應用程序時的故事板中,您只需要將rootviewcontroller分配給您的變量。 一種方法是:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var first: COBezierDemoViewController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        if let firstViewController = self.window?.rootViewController as? COBezierDemoViewController {
            self.first = firstViewController
        }

        return true
    }

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
        first?.fileurl(url)
    }
}

由於您的first對象是nil您應該首先使用以下代碼分配一個新對象

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {

        let first = FirstViewController()
        first.fileurl(url)
        return true
    }

您需要使用故事板。 使用故事板為ViewController提供標識符。

let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewControllerWithIdentifier("<Controller ID>") as FirstViewController
vc.fileurl(url)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM