[英]Passing information from a TableViewController to a DetailViewController
[英]send data from tableviewcontroller to detailviewcontroller
我有一個名為DetailTableViewController的tableviewcontroller,我需要將數據傳遞給名為DetailTableViewController的下一個tableviewcontroller。 但是我需要在用戶單擊DetailTableViewController的單元格時傳遞數據。 然后,我收到錯誤消息“在展開一個Optional值時意外發現nil”。請幫助我在Swift 3中進行分類。
首先,在這種情況下, 永遠不要從視圖(單元)獲取數據,而總是從模型(數據源數組)獲取數據。
其次, prepare(for segue
)的簽名對於Swift 3是錯誤的。
在didSelectRowAt
傳遞indexPath而不是self
,還可以刪除valueToPass
。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "Cell", sender: indexPath)
}
在prepareForSegue
,從模型中獲取數據並將其傳遞給詳細視圖控制器:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Cell" {
let viewController = segue.destination as! GuidesDetailsTableViewController
let indexPath = sender as! IndexPath
viewController.passedValue = guides[indexPath.row]
}
}
首先在詳細視圖控制器中創建一個變量,以保存從第一個視圖控制器發送的值。 然后在第一個視圖控制器中的didSelectRowAt
方法內分配值,然后以編程方式導航。 通過這種方式,您無需實現prepare for segue
方法來發送數據。
您只需要實現didselectrowat
方法。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selected = firstArray[indexPath.row]
let detailvc = self.storyboard?.instantiateViewController(withIdentifier: "DetailTableViewController") as! DetailTableViewController
detailvc.type = selected
self.present(detailvc, animated: true, completion: nil)
}
我從頭開始為您創建了一個視頻教程。 如何將數據從一個表視圖控制器傳遞到另一個 。 希望對您有幫助。
在didSelectRow
內部,您將設置一個新的indexPath
。 刪除它應該可以解決問題。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Don't reassign indexPath
// let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
performSegue(withIdentifier: "Cell", sender: self)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.