IOS - UIContainerView Embedded UIViewController software suite

I have UIViewController

to UIContainerView

inside. Based on whether some condition is true, I would like to programmatically set the inline view of the container to a different one UIViewController

. I noticed that you can only have one built-in segue to set one UIViewController

, so is there a way to do this?

I tried to set up my container view as an outlet, but I couldn't find any methods that set the inline UIViewController

. Any advice on how to get started with this would be appreciated.

+3


source to share


2 answers


I think your idea is wrong if you meant replacing UIViews

of UIViewController

(I hope I understood your concept).

A UIViewController

must have 1 constructed UIView

and must manage the values โ€‹โ€‹of this view. As you said, you can use Containers

, but you have to add UIViewController

with this view, so there is an instance that manages this view. Your first one UIViewController

should add / remove only ChildViewController

.

Therefore, I would advise:

Inject the category into the UIViewController and add the following methods:

- (void)displayContentController:(UIViewController *)content {
    [self addChildViewController:content];
    content.view.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:content.view];
    [content didMoveToParentViewController:self];
}

- (void)hideContentController:(UIViewController *)content {
    [content willMoveToParentViewController:nil];
    [content.view removeFromSuperview];
    [content removeFromParentViewController];
}

      



Create AViewController

and BViewController

. Into the AViewController

call (viewDidLoad?):

BViewController *bViewController = [[BViewController alloc] init];
[self displayContentController:bViewController];

      

To BViewController

control the view of this controller. AViewController

should only control when to show the BViewController and when to hide it.

If I misunderstood your question please comment on this, I will delete this answer.

+6


source


Inspired by Viv's answer:



extension UIViewController {

    func showContentController(_ controller: UIViewController, containerView: UIView? = nil) {
        controller.willMove(toParentViewController: self)
        self.addChildViewController(controller)
        controller.view.frame = (containerView ?? self.view).frame
        (containerView ?? self.view).addSubview(controller.view)
        controller.view.autoPinEdgesToSuperviewEdges()
        controller.didMove(toParentViewController: self)
    }

    func hideContentController(_ controller: UIViewController) {
        controller.willMove(toParentViewController: nil)
        controller.removeFromParentViewController()
        controller.view.removeFromSuperview()
        controller.didMove(toParentViewController: nil)
    }
}

      

0


source







All Articles