简体   繁体   中英

How to pass data from TableView cell to another viercontroller in Swift 5?

I am trying to pass data from TableView cell to another ViewController but on the other veiwcontroller passing value found nil. Here is the DidSelectRow code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    let vc = storyboard?.instantiateViewController(identifier: "Test") as? TestVC
    present(vc!, animated: true, completion: nil)
    
    vc?.Name = array_product_name[indexPath.row]
}

And here is the another ViewController code:

class TestVC: UIViewController {
@IBOutlet weak var nameLbl: UILabel!

var Name : String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    
    print("Product Name is:-\(Name)")
    nameLbl?.text = Name
}

Your first view controller code is fine. On the second one instead of setting values in viewDidLoad set those in viewWillAppear .

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