简体   繁体   中英

IOS/Swift: Pass Object in tableview to detail view controller

I am trying to grab an object from a tableview and pass it to a detail view, something I know how to do in Objective-C but am learning for first time Swift. However, my code is not getting the row from the index path or object.

Here is my code.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("segue")
        if segue.identifier == "showDetail"{
                    if let destinationVC = segue.destination as? detailVC {
                                    )
                if let indexPath = self.tableView.indexPathForSelectedRow {      
                    print("row%@",indexPath)//Prints as nil
                let thisItem = myItems[indexPath.row]//never gets here
    destinationVC.item = thisItem 
            }
        }
    }
    }

Can anyone see why I am not getting the row or the object? Thanks in advance for any suggestions.

Edit:

I got it to work with following:

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

            let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow! as NSIndexPath

            let anItem: myItem = myItems[indexPath.row];

            let destVC = segue.destination as? detailVC
            destVC?.item = anItem

        }
    }

Implement UITableViewDelegate method,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let item = myItems[indexPath.row]
    self.performSegue(withIdentifier: "showDetail", sender: item)
}

then implement below,

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showdetail" {
        let detailController = segue.destination as! detailVC
        detailController.item = sender as! Your_Item
    } 
}

Why don't you use these methods to save the value of the selected row or item? and then perform segue?

tableView(_:didDeselectRowAt:)
tableView(_:didSelectRowAt:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM