0

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

2
  • You need to add autolayout constraints. Commented Nov 23, 2015 at 13:13
  • Please add subview frame size code. Commented Nov 23, 2015 at 13:14

2 Answers 2

1

add following line in your code....

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

this will fix the problem.

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

6 Comments

I'm agree with @nhgrif, You have to use Auto layout.
Worked! I just changed the self.view.layer.bounds to the dedicated view it's being added to, so view.layer.bounds, and working like a charm! Thanks.
What's the difference between auto-layout and this?
@denislexic: This is matter of choice, but at the end you'll realise "Autolayout" is that how useful and great feature!
It's not a matter of choice. What happens when your parent view's size changes? Say, for example, when your app is launched on a new iPad Pro in split screen mode.
|
0

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

2 Comments

No... these autolayout constraints probably don't do anything different. He almost certainly needs to add autolayout constraints between the child view controller's view and the parent view he's adding it to...
@nhgrif Yes, He has to check by implementing required constraints for adding view. Answer is general guidelines to add view with constraints using VFL (Visual Formatting language), probably he'll use it in a way.

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.