Home > Mobile >  Swift Protocol Third VC to First VC
Swift Protocol Third VC to First VC

Time:07-29

I need to pass a String and Array from my Third ViewController to my First ViewController directly using protocol/delegate, I have no problem doing it from VC 2 to VC 1 but I'm having a hard time with this. Also after clicking a button in my VC3 I need to go back to VC 1 and update the VC UI how would I do that? Would that have to be in viewdidload? This in Swift UIKit and Storyboard

CodePudding user response:

What you need is unwind segue. Unwind segue will act like segue, only backward, popping, in this case, VC2. You can read here for more information.

Updating data code would be put in a function similar to prepareToSegue() but for unwind segue in your VC1. Example of the function inside VC1:

@IBAction func unwindToDestination(_ unwindSegue: UIStoryboardSegue) {
    switch unwindSegue.identifier {
    case SegueIdentifier.yourSegueIdentifier:
        let sourceVC = unwindSegue.source as! SourceVC
        dataToPass = sourceVC.dataToPass
        reloadData()
    default:
        break
    }
}

CodePudding user response:

You need two protocols, and your firstVC and SecondVC have to conform those. When pushing new ViewController you need to give the delegate of that ViewController to self. On your third VC, when you click the button you need to call your delegate and pass your data to that delegate method, then repeat the same for other.

For FirstVC

protocol FirstProtocol: AnyObject {
    func firstFunction(data: String)
}

class FirstVC: UIViewController, FirstProtocol {
    
    weak var delegate: FirstProtocol?

    @IBAction func buttonClicked(_ sender: Any) {
        let secondVC = SecondVC()
        secondVC.delegate = self
        navigationController?.pushViewController(secondVC, animated: true)
    }
    
    func firstFunction(data: String) {
        navigationController?.popToRootViewController(animated: true)
        print(data)
    }
}

You handle your navigation from your root. For better experience you can use something like coordinator pattern to handle it.

protocol SecondProtocol: AnyObject {
    func secondFunction(data: String)
}

class SecondVC: UIViewController, SecondProtocol {
    
    weak var delegate: FirstProtocol?
            
    @objc func buttonClicked() {
        let thirdVC = ThirdVC()
        thirdVC.delegate = self
        navigationController?.pushViewController(thirdVC, animated: true)
    }
    
    func secondFunction(data: String) {
        delegate?.firstFunction(data: data)
    }
}

Second VC is something that you just need to pass parameters.

class ThirdVC: UIViewController {
    
    weak var delegate: SecondProtocol?
    
    @objc func buttonClicked() {
        delegate?.secondFunction(data: "data") // PASS YOUR ARRAY AND STRING HERE
    }
}
  • Related