Swift delegate beetween two VC without segue

萝らか妹 提交于 2019-12-01 12:33:14
Wings

You need to create one more protocol in your SecondViewController to Pass that delegate from ThirdViewController to FirstViewController.

FirstViewController:

import UIKit

class ViewController: UIViewController, DataSentDelegate, dataSentDelegate  {

    @IBOutlet weak var imagefromThirdVC: UIImageView!

    var thirdVCImage: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func buttonTapped(_ sender: Any) { 
        let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func goToThirdVC() {
        let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func recievePhoto(data: UIImage) {
        thirdVCImage = data
        imagefromThirdVC.image = thirdVCImage
    }
}

SecondViewController:

import UIKit

protocol dataSentDelegate {
    func goToThirdVC()
}

class ViewController2: UIViewController {

    @IBOutlet weak var passingImage: UIImageView!

    var delegate: dataSentDelegate? = nil

    var images: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()

        images = UIImage(named: "screen")
    }

    @IBAction func actionButton(_ sender: Any) {
        self.delegate?.goToThirdVC()
    }

}

ThirdViewController:

import UIKit

protocol DataSentDelegate {
    func recievePhoto(data: UIImage)
}

class ViewController3: UIViewController {

    var delegate: DataSentDelegate? = nil

    @IBOutlet weak var passedImageView: UIImageView!

    var passedImage: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()

        passedImage = UIImage(named: "screen")
        passedImageView.image = passedImage
    }

    @IBAction func action(_ sender: Any) {

        let data = passedImageView.image
        delegate?.recievePhoto(data: data!)
        //   delegate?.goToFirstVC()

        guard let viewControllers = self.navigationController?.viewControllers else {
            return
        }

        for firstViewController in viewControllers {
            if firstViewController is ViewController {
                self.navigationController?.popToViewController(firstViewController, animated: true)
                break
            }
        }

    }

}

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