我有两个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。不确定是什么问题。
答案 0 :(得分:2)
在类范围/全局范围内编写prepareForSegue
。在你的代码prepareForSegue
中永远不会调用因为你在方法中写这个。在performSegue
中传递rowSelected并使用prepareForSegue
在sender
中获取rowSelected值,或者您可以使用indexPathForSelectedRow
的{{1}}属性。
tableView
答案 1 :(得分:1)
override
prepareForSegue
见下面的示例代码: -
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]
}
}
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