3

I have a UIStackView and I am dynamically adding UIViewControllers contained, here is my code;

[self addChildViewController:driverForm];
[self addChildViewController:marketingView];

[self.stackView insertArrangedSubview:driverForm.view atIndex:0];
[self.stackView insertArrangedSubview:marketingView.view atIndex:1];

[driverForm didMoveToParentViewController:self];
[marketingView didMoveToParentViewController:self];

After reading the documents it states I must call didMoveToParentViewController.

The problem I am facing is, the actions on the final UIViewController are not being called, but the first ViewController does. If I swap these round the first one works and the last one does not.

Adam Rush
  • 155
  • 3
  • 16
  • Just an update to this, I removed the UIStackView and do the same functionality but just adding directly to the UIScrollView and this worked. – Adam Rush May 04 '16 at 15:53

3 Answers3

2

Simply add the view of your ViewController to your UIStackView like this:

yourStackView.addArrangedSubview(yourViewController.view)

Also, you don't need to be worried about the view being nil as it always returns UIView!

Note that the order is reversed, so the last appears first. To address this, assuming you have an array of view controllers, you can use stride to traverse your array inversely and add view controllers to your stack.

Amin Tavassolian
  • 363
  • 3
  • 10
0

Here is a quick copy/pasta version for Swift 5:

private var childViewController: UIViewController
private var stackView: UIStackView?

// MARK: - UIViewController
    
override func loadView() {
    super.loadView()
    
    // 1. Add the child view controller to the parent.
    addChild(childViewController)
    
    // 2 Create and add the stack view containing child view controller's view.
    stackView = UIStackView(arrangedSubviews: [childViewController.view])
    stackView!.axis = .vertical
    self.view.addSubview(stackView!)
    
    // 3. Let the child know that it's been added!
    childViewController.didMove(toParent: self)
}
Zorayr
  • 23,770
  • 8
  • 136
  • 129
-4

UIStackView is for arranging multiple subviews in the same UIViewController class. how can you use it for different UIViewControllers?

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/#//apple_ref/doc/uid/TP40015256-CH1-SW31

Harris
  • 310
  • 3
  • 13
  • 1
    ChildViewControllers ? – Adam Rush May 04 '16 at 15:53
  • a UIViewcontroller controls the UIViews inside it in collaboration with the Data Model (properties methods etc) hence the name 'Controller'. The MVC paradigm? – Harris May 05 '16 at 08:03
  • 2
    View controller containers don't care where or how their children views are arranged. There's nothing wrong with parenting multiple children inside a single view controller and using a stack view to arrange their views. – CIFilter Dec 28 '16 at 15:49