NSGenericException', reason: 'Unable to install constraint on view

adevani11 picture adevani11 · Feb 12, 2013 · Viewed 28.9k times · Source

Terminating app due to uncaught exception 'NSGenericException'

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: view:; layer = ; contentOffset: {0, 0}>'

Answer

ipmcc picture ipmcc · Feb 12, 2013

You need to install the constraint on the "higher" of the two views. A good, general way to do this is like this:

NSLayoutConstraint* constraint = ...;
NSView* firstView = constraint.firstItem;
NSView* secondView = constraint.secondItem;    
[[firstView ancestorSharedWithView: secondView] addConstraint: constraint];

Just a word of caution: It's good to remember here that constraint attributes are evaluated in the context of the view on which they are added. So for instance, the value of NSLayoutAttributeLeft of viewA, for a constraint installed on viewB, is interpreted in the coordinate space of viewB. For constraints that only reference sibling views or their superview, that fact is largely irrelevant, but there's no restriction that constraints can't reference two views that aren't siblings or direct parents.