通过prepareForSegue传递NSString - Swift

时间:2014-08-18 15:55:18

标签: ios uiviewcontroller swift segue modalviewcontroller

我试图通过使用prepareForSegue方法将字符串传递给下面看到的Modal视图控制器。见下文:

这是我的初始视图控制器,我将在其中呈现模态视图:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

    if segue.identifier == "newProject" {
        var newProjectVC:ModalViewController = ModalViewController()
        newProjectVC = segue.destinationViewController as ModalViewController
        newProjectVC.testString = "hello"
    }
}

这是我的模态视图控制器:

import UIKit

class ModalViewController: UIViewController {

    var testString:NSString!

    override func viewDidLoad() {
        println(self.testString)
    }
}

以下是故事板中的内容: ![在此输入图像说明] [1]

问题是它在这一行引发了异常:

    newProjectVC = segue.destinationViewController as ModalViewController

我觉得它可能与导航控制器有关,但我不确定,有什么想法吗?

1 个答案:

答案 0 :(得分:13)

你是对的destinationViewController是导航控制器而不是ModalViewController,试试这个:

let navigationController = segue.destinationViewController as UINavigationController
let newProjectVC = navigationController.topViewController as ModalViewController
newProjectVC.testString = "hello"