以下是我目前的代码:
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是否为零?为什么呢?
答案 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拖动到新视图即可。