Search code examples
iosswiftcontainerssegueviewcontroller

Passing Data with without Segue from Container View to MainVC


Idea to send value trackNumber after pressing the button in the Container View(with ViewController) to Main ViewController to recivedTrackNumber without segue because they are in the same view. How to inform Main View controller(recivedTrackNumber) about the value of trackNumber ?

Container View(with ViewController) looks like that with button

 import UIKit
 class SelectSoundVC: UIViewController {

   var trackNumber: Int!

   @IBAction func winterSoundBut(_ sender: UIButton) {
    trackNumber = 1

  } 

}

and Main ViewController

class MainVC: UIViewController {

   var recivedTrackNumber: Int!

}

Main.storyboard Screenshot


Solution

  • Delegate pattern should help you. First of all you need the delegate protocol:

    protocol SelectSoundVCDelegate {
        func didSelectTrackNumber(_ trackNumber: Int)
    }
    

    with func that accept the trackNumber value. Next, you need to create delegate property in SelectSoundVC:

    class SelectSoundVC: UIViewController {
    
        weak var delegate: SelectSoundVCDelegate?
        var trackNumber: Int!
    
        @IBAction func winterSoundBut(_ sender: UIButton) {
            trackNumber = 1
            delegate?.didSelectTrackNumber(trackNumber)
        } 
    
    }  
    

    that will be call the didSelectTrackNumber in @IBAction. Note that delegate property should be weak to avoid reference cycles. The last step, in MainVC you should set delegate property of SelectSoundVC:

    selectSoundVC.delegate = self  
    

    This part is little bit tricky, because you need the instance of SelectSoundVC to set the delegate. You can set it in prepareFoSegue method, for example:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let viewController = segue.destination as? SelectSoundVC, segue.identifier == "SelectSoundVC" {
            viewController.delegate = self
        }
    }