使用Swift 2.0在segue之间传递数据

时间:2016-02-26 03:20:06

标签: ios uinavigationcontroller swift2 segue

我似乎正在按照教程开发,但我无法将数据传递给我的第二个视图控制器而不是零。 我是Swift的新手,所以我可能也没有正确使用选项。以下是我设置代码的方法。

import UIKit

class DetailsViewController: UIViewController {

    var book : PLBook?

    override func viewDidLoad() {
        super.viewDidLoad()
        //View Did Load
        print(self.book)
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
}

然后这就是我如何呈现第二个视图控制器并准备segue。

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("toDetailVC", sender:self)
    }

    //MARK: Navigation

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "toDetailVC"){
            //prepare for segue to the details view controller

            if let detailsVC = sender?.destinationViewController as? DetailsViewController {
                let indexPath = self.tableView.indexPathForSelectedRow
                detailsVC.book = self.books[indexPath!.row]
            }

        }
    }

在第二个视图控制器中,book var始终为nil。我有什么想法可以让数据通过?

2 个答案:

答案 0 :(得分:3)

试试这个:

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

if (segue.identifier == "toDetailVC") {

 //prepare for segue to the details view controller

           let detailsVC = segue.destinationViewController as!  DetailsViewController

            let indexPath = self.tableView.indexPathForSelectedRow
            detailsVC.book = self.books[indexPath!.row]

}

答案 1 :(得分:1)

您应该使用segue.destinationViewController,而不是sender?.destinationViewController