简体   繁体   中英

How to pass data to a embedded UIViewController in side a UIView - Swift 5

There's a view controller B. So, have embedded B as child view controller in viewController A in a UIView. Now, need to call a api in child view controller B when it is added as a child. So, need to set a check when added B as child only then this api need to be hit. Kindly help in this.

Below is the code, how i embedded B as child View in A viewController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vcController: UIViewController = storyboard.instantiateViewController(withIdentifier: "BNameViewController") as! BNameViewController

    //add as a childviewcontroller
    addChild(vcController)

     // Add the child's View as a subview
     viewBList.addSubview(vcController.view)
    vcController.view.frame = viewBList.bounds
     vcController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

     // tell the childviewcontroller it's contained in it's parent
    vcController.didMove(toParent: self)

viewBList is the UIView in View controller A. So, now need in this case an api to be called in VC B not when we navigate to B from any other VC. I tried passing a bool or string by declaring same in VC B and the pass value from A, that doesn't work. Please guide. Hope i made my question clear, please feel free to ask if any doubt.

There are so many ways to do this, When you are navigating to view controller B from some other view controller then you have navigationController property not nil.

In that case you can check like that

override func viewDidLoad(animated: Bool) {
    super.viewDidLoad(animated: animated)
    //If navigating from some view controller then 
    if self.navigationController != nil {
        //Code here for case, when you are navigating from some one 
    }

    //View controller is  child of someone
    if (self.navigationController == nil || self.presentingViewController == nil || self.parent != nil ) {
        //This is your case, 
        // hit api here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM