1

I am a newbie to Swift. I have started a new project with Swift. I am trying to add SecondViewcontroller view as a subview to the FirstViewController. What i am looking is to declare the SecondViewController property for the FirstViewController. Can anyone please suggest the Swift version of the below code

FirstViewController.h

@interface FirstViewController : UIViewController {
    IBOutlet UIView *listContainerView;
}

@property (nonatomic, strong) SecondViewController *secondVC;

@end

FirstViewController.m

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    self.secondVC  = (SecondViewController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"SecondViewController"];

    if (![self.secondVC.view isDescendantOfView:self.view]) {
        [self addChildViewController:self.secondVC];
        self.secondVC.view.frame = CGRectMake(0, 0, listContainerView.frame.size.width, listContainerView.frame.size.height);
        [listContainerView addSubview:self.secondVC.view];
        [self.secondVC didMoveToParentViewController:self];
     }
}

@end

1 Answer 1

1

What you should do is to make a subview, instead of making a new UIViewController. In only very special cases would you ever put one UIViewController inside another. Basically every 'screen' should have one UIViewController, but you shouldn't put one inside another.

Sign up to request clarification or add additional context in comments.

6 Comments

Not necessary, there a lot of architectures that use childViewControllers (just to remain in the Apple framework, the Navigation controller do the same). I think that he is asking only for a conversion from his objective-c code to the swift version.
@MarcoPace but as a beginner, nesting view controllers is rarely ever used and that what he's trying to accomplish is probably to segue to another view. Not trying to assume, but helping on bad app models that encapsulate views on top of one another through child VCs isn't necessarily good for OP.
Oh, looking from that point of view probably you were right :)
Another instance where (although a subclass) you would use one viewController in another is dealing with pageViewControllers, tableViewControllers etc... But yeah, I kinda do agree with you on the "make a subview" standpoint
var SecondViewController = SecondViewController()?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.