在 tableView 中的 didSelectRow 之后 indexPath 为 nil

indexPath is nil after didSelectRow in tableView

我想将所选行传递给下一个 VC。 但它始终为零,无论单击哪一行。 我很高兴得到任何提示。

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

        self.performSegue(withIdentifier: "goToDetails", sender: self)
        
        
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

您可以传递索引路径而不是 self

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "goToDetails", sender: indexPath) 
}

并在 prepare(for 中获取它,顺便说一句,标识符与 performSegue 的标识符不匹配,也在故事板中检查它

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let indexPath = sender as? IndexPath { ...

但是如果 segue 是从 table 视图单元连接到目标控制器而不是从视图控制器连接,您可以删除 didSelectRow 并且 sender 参数包含所选单元格

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails", 
       let cell = sender as? UITableViewCell,
       let indexPath = collectionTableView.indexPath(for: cell) { ...

使用您的 IndexPath 作为发件人

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

    self.performSegue(withIdentifier: "goTo Details", sender: indexPath)

}

然后在你的prepare(for segue:)上获取索引路径如下

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goTo Details",
       let destinationVC = segue.destination as? DetailsViewController,
       let indexPath = sender as? IndexPath {

        //Whatever you do with indexPath

    }
}