user1688346
user1688346

Reputation: 1970

Add constraint programmatically

I have a collectionview and other views inside a scrollview. I need to add constraint programmatically to make sure it works on all devices.

CollectionView/Gallery is inside the UIScrollView. It works before the constraint.

I am using the code below to stick the collectionview to the right but I am getting error terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal. constraint:

//constraint
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:self.galleryView
                                                                         attribute:NSLayoutAttributeRight
                                                                         relatedBy:NSLayoutRelationEqual
                                                                            toItem:self.scrollView
                                                                         attribute:NSLayoutAttributeRight
                                                                        multiplier:1.0
                                                                          constant:0.0];
[self.galleryView addConstraint:bottomSpaceConstraint];

Upvotes: 1

Views: 783

Answers (1)

uchuugaka
uchuugaka

Reputation: 12782

Constraints other than height and width must be added to the containing view or highest in the hierarchy.

You might find that scroll views don't make it easy or clear how to set up constraints for the items inside.

In that case, you either do the old school thing for scroll view content or you create an intermediate view inside the scroll view document view.

Scroll views are tricky because they have a clip view that determines how much of the document view is visible.

Upvotes: 1

Related Questions