我对如何处理快速协议以在两个视图控制器之间传递数据有基本的了解。我的情况是这样的:我想将数据传递回我的第一个ViewController。
例如:
第一个ViewController
class ViewControllerA: UIViewController, ViewControllerCResult {
func set(data: String) {
}
}
第二个ViewController
class ViewControllerB: UIViewController {
}
第三ViewController
protocol ViewControllerCResult {
set(data: String)
}
class ViewControllerC: UIViewController {
var delegate: ViewControllerCResult?
}
ViewControllerA-> ViewControllerB-> ViewControllerC
我想将数据从ViewControllerC传递到ViewControllerA。 有人可以帮我吗?
答案 0 :(得分:1)
您可以从控制器A-> B-> C传递Delegates
,并且将调用popViewcontroller时,您可以在ViewController C中检查self.delegate
,如果它存在,则只需像这样{{ 1}}。检查
ViewController3中的popControllerPressed函数
第一视图控制器
ViewController类:UIViewController,ViewControllerCResult {
self.delegate?.set("data from c")
第二个ViewController
var delegate: ViewControllerCResult?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushControllerPressed(_ sender: Any) {
if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController2") as? ViewController2 {
if let navigator = navigationController {
viewController.delegate = self
navigator.pushViewController(viewController, animated: true)
}
}
}
func set(data: String) {
}
}
第三ViewController
class ViewController2: UIViewController, ViewControllerCResult {
var delegate: ViewControllerCResult?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushControllerPressed(_ sender: Any) {
if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController3") as? ViewController3 {
if let navigator = navigationController {
viewController.delegate = self.delegate
navigator.pushViewController(viewController, animated: true)
}
}
}
func set(data: String) {
print(data)
}
}
ViewController3类:UIViewController,ViewControllerCResult {
protocol ViewControllerCResult {
func set(data: String)
}
这里是代码链接:Pass data forth and back