denislexic
denislexic

Reputation: 11392

Adding Subview creates layout issue

I'm programmatically adding a view inside another view like so:

func addViewControllerToSpecificView( view: UIView, controller: UIViewController) {
        controller.willMoveToParentViewController(self)
        view.addSubview(controller.view)           
        self.addChildViewController(controller)
        controller.didMoveToParentViewController(self)
    }

The issue is that the parent view ends up being wider than it should be (the width of the screen).

When I don't load the subview using the above method, the positioning is perfect (no extra padding). I have no idea why it's adding an extra ~30px

enter image description here

Upvotes: 0

Views: 79

Answers (2)

Abhishek
Abhishek

Reputation: 509

add following line in your code....

controller.view.frame = self.view.layer.bounds;

this will fix the problem.

Upvotes: 1

Mehul Patel
Mehul Patel

Reputation: 23053

I dont know that are you adding Auto layout constraint for this view.

Please check that this layout constraints are added in your code, if not then add below constraint after you add childViewController.

let metrices = ["width" : view.bounds.size.width, "height" : view.bounds.size.height]

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[childView(width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrices, views: ["childView" : controller.view]))

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[childView(height)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrices, views: ["childView" : controller.view]))

Upvotes: 0

Related Questions