Prepareforsegue没有将适当的值传递给目标Viewcontroller?

时间:2016-11-14 05:08:27

标签: swift xcode

我有两个viewcontrollers(一个是tableVC),我想在它们之间传递信息。这是来自tableVC的代码:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        var rowSelected = indexPath.row
        print(rowSelected) //always returns the correct integer

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

            let destViewController: newController = segue.destination as! newController
            newController.rowSelected = rowSelected
        }

        performSegue(withIdentifier: "rowSelected", sender: Any?.self)//segue to newController

    }

以下是我希望将信息传递给newController的代码:

 @IBOutlet weak var label: UILabel!

var rowSelected = Int()
override func viewDidLoad() {
    super.viewDidLoad()

    label.text = infoArray[rowSelected]

    print(rowSelected) //always logs 0 to the console, regardless of cell selection

}

我以为我已经适当地设置了它,但无论出于何种原因,无论在tableVC中选择了什么单元格,调用infoArray的索引始终为0。不确定是什么问题。

2 个答案:

答案 0 :(得分:2)

在类范围/全局范围内编写prepareForSegue。在你的代码prepareForSegue中永远不会调用因为你在方法中写这个。在performSegue中传递rowSelected并使用prepareForSeguesender中获取rowSelected值,或者您可以使用indexPathForSelectedRow的{​​{1}}属性。

tableView

答案 1 :(得分:1)

override

时,需要在函数中使用prepareForSegue

见下面的示例代码: -

Swift 3

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "ShowAttractionDetails" {

       let detailViewController = segue.destination
            as! AttractionDetailViewController

       let myIndexPath = self.tableView.indexPathForSelectedRow!
       let row = myIndexPath.row
       detailViewController.webSite = webAddresses[row]
    }
}

Swift 2.3

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

           let detailViewController = segue.destination
                as! AttractionDetailViewController

           let myIndexPath = self.tableView.indexPathForSelectedRow!
           let row = myIndexPath.row
           detailViewController.webSite = webAddresses[row]
        }
    }

来源 - Segue from UITableViewCell Taps in Swift& TableView Navigation using Storyboards in Xcode 8