iewController的过程中将值从ViewControll

iewController的过程中将值从ViewControll

本文介绍了如何在使用Swift消除ViewController的过程中将值从ViewController B传递给ViewController A?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是,我试图在关闭视图控制器的过程中将值从 ViewController B 传递给 ViewController A 。在这里,我使用了下面的代码,但无法在 ViewController A 中获取值。

My scenario, I am trying to pass the value from ViewController B to ViewController A during dismiss the view controller. Here I used below code but I can’t able to get the value in ViewController A.

ViewController B

// protocol used for sending data back
protocol isAbleToReceiveData {
    func pass(data: String)  //data: string is an example parameter
}

// Making this a weak variable so that it won't create a strong reference cycle
var delegate: isAbleToReceiveData?

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        self.delegate?.pass(data: "someData") //call the func in the previous vc
}

@IBAction func Click_action(_ sender: Any) {
        self.dismiss(animated: false, completion: nil)
        self.delegate?.pass(data: "someData")
 }

ViewController A

class MyViewController: UIViewController, isAbleToReceiveData {

func pass(data: String) {
        print("USER: \(data)")
    }
}

// MARK: FromTouch Action
    @objc func fromTouchTapped(_ sender: UITapGestureRecognizer) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "ViewControllerB")
        viewController.modalTransitionStyle = .crossDissolve
        let navController = UINavigationController(rootViewController: viewController)
        present(navController, animated: true, completion: nil)
    }


推荐答案

一切都很好,您错过了 ViewControllerA 并在 ViewControllerB中分配委托

Everything is right you missed assign delegate in your ViewControllerA while present ViewControllerB.

if let VC_B = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB{
    VC_B.delegate = self
    VC_B.modalTransitionStyle = .crossDissolve
    self.present(VC_B, animated: true, completion: nil)
}

注意

instad

let viewController =
self.storyboard?.instantiateViewController(withIdentifier:
ViewControllerB)

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerB")

这篇关于如何在使用Swift消除ViewController的过程中将值从ViewController B传递给ViewController A?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:05