返回上一个屏幕时如何在控制器之间传输数据?迅速

时间:2019-05-08 13:16:21

标签: ios swift realm

在应用程序中,要求我选择一个类别,当我单击时,我从tableView移到下一个屏幕,当我单击所需的类别时,应将其保存并返回到上一个控制器,在该位置而不是“选择类别”,而是我选择的类别。

我通过此方法navigationController?.popViewController(animated: true)使用,这使我回到最后一个屏幕。 据我了解,prepare不被调用,但是由于我确切地知道要去的地方,因此我可以在调用pop ...的方法中访问要切换到的控制器,并将其传递给必要的控制器。属性?但是如何?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  let currentCell = categories[indexPath.row]
    /?
    /?
  navigationController?.popViewController(animated: true)
}

3 个答案:

答案 0 :(得分:3)

当您进入选择屏幕时,请执行

let vc = ///
vc.delegate = self
// push

然后在didASelectRowAt

class CategoryViewController:UIViewController {
 weak var delegate:PreviousVC?
 ////
}

delegate?.sendData(someData)
navigationController?.popViewController(animated: true)

didASelectRowAt内的另一个选项

// access previous vc
let previousVC = self.navigationController!.viewControllers[self.navigationController!.viewControllers.count - 2] as! PreviousVc
previousVC.sendData(someData)
// pop here

编辑:在第一个VC中

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondViewController {
          secondVC.delegate = self   
        }
    }

答案 1 :(得分:0)

您可以使用闭包将所选类别传递给上一个视图控制器

class FirstViewController: UIViewController {   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondViewController {
            secondVC.selectedOption = { selectedOption in
                print(selectedOption)
                //change category title here
            }
        }
    }

}
class SecondViewController: UIViewController {
    var selectedOption: ((String) -> Void)?
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedOption?("Selected Option String")
        navigationController?.popViewController(animated: true)
    }
}

答案 2 :(得分:0)

当您移至

之类的类别选择控制器时,也许应该传递“完成处理程序”
(String)->(Void)

并在将其弹出时在此Clouser中传递类别