繁体   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