Passing Data Between Controllers in Swift

落爺英雄遲暮 提交于 2020-01-06 22:42:00

问题


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
}

回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/41209776/passing-data-between-controllers-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!