Search code examples
iosswift3xcode8

how to send data from popover view controller to main view controller. Pass a string so that i can make that as the label text in the main view


I tried many methods to send data from my popup view controller to main view controller. but failed. can anybody help me with this. i am using a "present as popover" segue. i want to the text entered in textfield of popover view as the label text of main view.


Solution

  • From Popup View, Data send to Main ViewController using protocol in Swift 3. enter image description here Complete Details are given below... 1. View Controller Implementing with Protocol named sendDataToViewProtocol.

    import UIKit
     class ViewController: UIViewController,sendDataToViewProtocol {
    
     @IBOutlet weak var lshowDataLabel: UILabel!
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    @IBAction func btnShowPopUpDialog(_ sender: Any) {
        let popUpVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopupVIewController") as! PopupVIewController
        //Don't forget initialize protocal deletage
        popUpVc.delegate = self
        self.addChildViewController(popUpVc)
        popUpVc.view.frame = self.view.frame
        self.view.addSubview(popUpVc.view)
        popUpVc.didMove(toParentViewController: self)
    }
    
    func inputData(data: String) {
        lshowDataLabel.text = data
    
    }
    }
    
    1. Popup View Controller With Protocol named sendDataToViewProtocol below. 3.protocol declare outside the PopupVIewController.
    2. Don't forget to assign ViewController to PopupVIewController .
    3. In viewController withIdentifier: "PopupVIewController" , "PopupVIewController" is PopupVIewController storyborad Id.
    4. Please see the attached image.

       import UIKit
      
       protocol sendDataToViewProtocol {
         func inputData(data:String)
       }
      
      class PopupVIewController: UIViewController {
      //Protocol object
       var delegate:sendDataToViewProtocol? = nil
      
       @IBOutlet weak var txtInputFieldText: UITextField!
       override func viewDidLoad() {
       super.viewDidLoad()
       self.view.backgroundColor = UIColor
       .black.withAlphaComponent(0.8)
       }
      
       @IBAction func btnSendDataToViewController(_ sender: Any) {
       //"Check Delegate nil"
       if(delegate != nil){
           //Check textField is empty
          if(txtInputFieldText.text != ""){
              //set textField Data to protocol Function
              delegate?.inputData(data: txtInputFieldText.text!)
              self.view.removeFromSuperview()
          }
      
        }
       }
      
       @IBAction func btnClose(_ sender: Any) {
         self.view.removeFromSuperview()
       }
      
      }