snapchatdotcom snapchatdotcom - 3 months ago 23
iOS Question

Adding a container view programmatically without storyboard?

I have this in my

viewDidLoad
:

let childViewControllerForPosts = PostsCollectionViewController(collectionViewLayout: UICollectionViewLayout())
let cView = childViewControllerForPosts.view
self.view.backgroundColor = UIColor.redColor()
self.addChildViewController(childViewControllerForPosts)
self.view.addSubview(cView)
childViewControllerForPosts.didMoveToParentViewController(self)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleScroll(_:)), name: "cvScrolled", object: nil)

cView.widthAnchor.constraintEqualToConstant(view.frame.size.width).active = true
cView.heightAnchor.constraintEqualToConstant(view.frame.size.height).active = true
cView.topAnchor.constraintEqualToAnchor(containerForGreyAndPurple.bottomAnchor).active = true
cView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true


However, I get an error saying that this is an illegal constraint because it has no common ancestor :(

Here's the error:

...because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal.'

Answer

You are setting the constraints incorrectly.

You need to first add constraints with parent view and container view, then you also need to add constraints to your container controller. Finally you should add the didMoveToParent in the end of setting all the constraints.

The example is as follows, you can do a similar thing in your case.

   NSLayoutConstraint.activateConstraints([
        containerView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 10),
        containerView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -10),
        containerView.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 10),
        containerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: -10),
    ])


  NSLayoutConstraint.activateConstraints([
        controller.view.leadingAnchor.constraintEqualToAnchor(containerView.leadingAnchor),
        controller.view.trailingAnchor.constraintEqualToAnchor(containerView.trailingAnchor),
        controller.view.topAnchor.constraintEqualToAnchor(containerView.topAnchor),
        controller.view.bottomAnchor.constraintEqualToAnchor(containerView.bottomAnchor)
    ])


controller.didMoveToParentViewController(self)

Use autolayout to set dynamic UIView to match container view

Comments