0

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.'

1 Answers1

1

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

Community
  • 1
  • 1
Harsh
  • 2,852
  • 1
  • 13
  • 27
  • Oh, I had to add my controller to a UIView? Because I added a UIView on the top half part of my screen, and then I attempted to just add the controller (the container) to the bottom. –  Aug 13 '16 at 20:33
  • 1
    No No.. what i gave you was just an example. You need to configure your container, architecturally similar, but you can have it set to different UIViews. – Harsh Aug 13 '16 at 20:35