How to transfer data between Parent and Child View Controllers

前端 未结 3 464
难免孤独
难免孤独 2021-01-26 18:32

I have tried looking at answers on similar questions to this, but I am not particularly experienced and have had trouble following them, so any help would be much appreciated!

3条回答
  •  终归单人心
    2021-01-26 18:48

    Try This.

    First Create Public Method For Add And Remove childVC.

    For Add childVC.

    public class func openChildViewController(parentVC:UIViewController, with childVC:UIViewController){
    
            parentVC.addChildViewController(childVC)
            childVC.view.frame = parentVC.view.frame
            parentVC.view.addSubview(childVC.view)
            parentVC.didMove(toParentViewController: childVC)
        }
    

    For Remove childVC.

       public class func removeChildViewController(childVC:UIViewController){
    
            childVC.willMove(toParentViewController: nil)
            childVC.view.removeFromSuperview()
            childVC.removeFromParentViewController()
        }
    

    Use Above Method.

    1.ParentVC.swift

    class ParentVC: UIViewController , ChildVCDelegate  {
    
         var arrType = NSMutableArray()
    
        //add ChildVC
        @IBAction func btnAddChildVC(_ sender: UIButton) {
            let ChildVC = self.storyboard?.instantiateViewController(withIdentifier: "ChildVC") as! ChildVC
            PickerVC.arrPass = arrType //for data passing create any object in ChildVC for ex. arrPass is NSMutableArray
            ChildVC.delegate = self
            openChildViewController(parentVC: self, with: ChildVC)
        }
    
         // MARK: ChildVC Delegate
       func SetSelectedPickerValue(strSelectOption: String) {
                    print(strSelectOption)
            }
        }
    
    }
    

    2.ChildVC.swift

    class ChildVC: UIViewController{
    
        // MARK: Variable for ParentVCData Passing
         var arrPass = NSMutableArray()
    
        override func viewWillAppear(_ animated: Bool) {
            print(arrPass)
        }
    
        //Remove ChildVC
        @IBAction func btnRemoveChildVC(_ sender: UIButton) {
            self.delegate?.SetSelectedPickerValue!(strSelectOption: “any String you pass ChildVC To ParentVC”)
            removeChildViewController(childVC: self)
        }
    }
    // MARK: Create Delegate Method
    @objc protocol ChildVCDelegate{
         @objc optional func SetSelectedPickerValue(strSelectOption:String)
    }
    

提交回复
热议问题