使用Swift和Storyboard在两个UIViewControllers之间传递数据

时间:2014-12-11 10:36:56

标签: ios uitableview swift

我使用下面的代码选择UITableView在UIViewControllers之间传递数据

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
    }
}

如何使用swift和tableView选择的数据做同样的事情?

我尝试过以下方法来进行简单的传递
但如何复制上述案例。

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

    var detailsVC = segue.destinationViewController as SecondViewController

    detailsVC.passedString = "hello"

}

2 个答案:

答案 0 :(得分:4)

这应该有效:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showRecipeDetail" {

            var detailsVC = segue.destinationViewController as SecondViewController
            let indexPath = tableView.indexPathForSelectedRow()
            detailsVC.passedString = recipes![indexPath?row]
            //or try that if above doesn't work: detailsVC.passedString = recipes[indexPath?row]
        }
    }
}

这一行可能需要修改:

destViewController?.destViewController.recipeName = recipes![i]

这取决于你的属性是否可选(也许你必须删除?或!)

答案 1 :(得分:0)

试试这个......如果您是第一个视图控制器嵌入在导航控制器中,您可以在didSelectRowAtINdexPath委托上推送第二个视图控制器,如下所示...

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Create a storyboard instance.....
    var storyBoard = UIStoryboard(name: "Main", bundle: nil)
    // Create a SecondViewController instance, from the storyboardID of the same.
    var seconVC = storyBoard.instantiateViewControllerWithIdentifier("seconViewControllerID") as SecondViewController
    seconVC.passedString = receipes[indexPath.row] as String
    self.navigationController?.pushViewController(secondVC, animated: true)
}