简体   繁体   中英

Passing Data Between Controllers in Swift

I want to passing data between TableViewController and ViewController the program does not go into the method My swift code:

    override func unwind(for unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {

    let destView : ViewController = unwindSegue.destination as! ViewController

    destView.min = Int(minTable)

    destView.tableText = unitsText
}

I take data:

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

    let  tableCell = moneyArray[indexPath.row]

    minTable = tableCell.val

    unitsText = tableCell.name

    let _ = navigationController?.popViewController(animated: true)
}

Adn my Table Code:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! TableViewCell

    let  tableShow = moneyArray[indexPath.row]

    cell.nameCurrency?.text = tableShow.name
    cell.valueCarrency?.text = "\(tableShow.val)"

    return cell
}

If you want to open a detail view controller when the user clicks on a cell in your main table view controller then the proper way to pass data is by using something like the following:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "MyDetailView") {
        // pass data to next view
        if let viewController: MyDetailsViewController = segue.destinationViewController as? MyDetailsViewController {
            viewController.units = mySelectedTableCell.unitsName
        }
    }
}

Full docs here .

You are using popViewController on your didSelectRow, that means that you are returning on your navigation controller and not pushing a unwind segue or any segue, so you cant use prepareForSegue/unwind method.

One correct way of solving this is using delegation.

You can find more information about that here: Passing data back from view controllers Xcode

But if you want to use unwind segue, you will have to write your unwind method on the previous viewController, not your current. Also you will need to use the method performSegue with the identifier of your unwind segue.

You can see more information about unwind segues here: What are Unwind segues for and how do you use them?

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