尝试将变量传递给具有segue

时间:2016-07-23 17:28:47

标签: ios swift uitableview segue uistoryboardsegue

以下是我目前的代码:

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?
}

正如你所看到的,我已经分配了#34; test"在didSelectRowAtIndexPath中的valueToPass,但在prepareForSegue中,valueToPass是否为零?为什么呢?

1 个答案:

答案 0 :(得分:1)

尝试更换:

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)

}

此外,当您在故事板中创建segue时,请确保您没有从tableview拖动到下一个viewcontroller。这是因为如果你自动执行此操作,那么执行segue将被称为BEFORE didSelectRow ...使其在设置值之前执行segue。只需从承载表视图的viewcontroller拖动到新视图即可。