Search code examples
iosswiftscrollview

Is there a way to connect or access my `scrollView`from my main class to another class?


in my MainViewController I have a scrollView and add a ChildView in it which works fine. In this example I instantiate my PlansViewController2and add it as a ChildViewto my scrollView.

enter image description here

After selecting a Cellit pushes a new controller. But I want to add the new Controller as a ChildView to my `scrollView.

enter image description here


  @IBAction func planAction(_ sender: UIButton) {
    let newPlan = sender.frame.origin.x
    scrollView.subviews.forEach{$0.removeFromSuperview()}
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let nextController = storyBoard.instantiateViewController(withIdentifier: "PlansViewController2") as! PlansViewController2
    addChildView(viewController: nextController, in: scrollView)
    self.movingView.frame.origin.x = newPlan
}

Im my PlansViewController2 I push another ViewControllerbut I want to add it also in my scrollView from the previous controller.

let storyBoard = UIStoryboard(name:"Main", bundle:nil)
            let planViewCtrl = storyBoard.instantiateViewController(withIdentifier: "PlanViewCtrl") as! PlanViewController
            planViewCtrl.navigationItem.title = plan.title
            self.show(planViewCtrl, sender: self)
            _ = planViewCtrl.view // force view loading, so we can set it up properly
            _ = self.updateLastUsed(plan: plan)
            planViewCtrl.plan = plan

Is it possible to add - in my case here - the PlanViewController into my scrollViewfrom my MainViewController?


Solution

  • When you add view's PlansViewController2 to scrollview. Please add PlansViewController2 to childViewController of VC has scrollView(self.addChild(nextController)). When you want to add PlanViewController to scrollView:

    • Step 1: First you need to get viewcontroller that have scrollView using parent property (self.parent).
    • Step 2: Final, You have access to scrollView instance though vc you get in step 1.

    Good luck!