Adam Rush
Adam Rush

Reputation: 155

Multiple ViewControllers contained in a UIStackView

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.

Upvotes: 3

Views: 4116

Answers (3)

Zorayr
Zorayr

Reputation: 24922

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)
}

Upvotes: 1

Amin Tavassolian
Amin Tavassolian

Reputation: 383

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.

Upvotes: 2

Harris
Harris

Reputation: 310

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

Upvotes: -4

Related Questions