ios - 使用 Swift 和 Storyboard 在两个 UIViewController 之间传递数据

标签 ios uitableview swift

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

- (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"

}

最佳答案

这应该有效:

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]

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

关于ios - 使用 Swift 和 Storyboard 在两个 UIViewController 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420772/

相关文章:

c# - Unity iOS 异常中的 XML 序列化

iphone - UITableView 将行锚定到底部

ios - 如何使用 ReactiveCocoa 处理无效 token

iphone - 页面控制导航符号?

ios - 将 RACComand 绑定(bind)到 UIViewController 事件

ios - 将数据从自定义表格 View 单元格传递到 UIView Controller

ios - 如何从 Parse 查询中获得超过 1000 个结果?

ios - SpriteKit、XCode 8、Swift 3 MGGetBoolAnswer 在模拟器中不可用

ios - NSFetchController 和 coredata 中的多对多

ios - 随机 UISearchDisplayController 崩溃 (iOS 7)