尝试将变量传递给带有 segue 的视图控制器时变量 nil

Variable nil when trying to pass variable to view controller with segue

这是我目前拥有的代码:

var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var viewController = segue.destinationViewController as AnotherViewController
    viewController.passedValue = valueToPass // valueToPass equals nil here? Why?
}

如您所见,我已将 "test" 分配给 didSelectRowAtIndexPath 中的 valueToPass,但在 prepareForSegue 中,valueToPass 为零?为什么?

尝试替换:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

有了这个:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

    let currentCell = tableView.cellForRowAtIndexPath(indexPath.row) as! UITableViewCell;

    valueToPass = currentCell.textLabel.text! // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

此外,当您在情节提要中进行转场时,请确保您没有从 table 视图拖到下一个 viewcontroller。这是因为如果您自动执行此操作,那么将在 didSelectRow 之前调用 perform segue... 使其在您设置值之前执行 segue。只需从承载 table 视图的 viewcontroller 拖动到新视图。