NSGenericException',原因:'无法在视图上安装约束

ade*_*i11 26 iphone objective-c ios6 xcode4.5

因未捕获的异常'NSGenericException'而终止应用程序

由于未捕获的异常'NSGenericException'而终止应用程序,原因:'无法在视图上安装约束.约束是否引用了视图子树之外的内容?那是违法的.约束:view:; layer =; contentOffset:{0,0}>'

ipm*_*mcc 44

您需要在两个视图的"更高"上安装约束.一个好的,通用的方法是这样的:

NSLayoutConstraint* constraint = ...;
NSView* firstView = constraint.firstItem;
NSView* secondView = constraint.secondItem;    
[[firstView ancestorSharedWithView: secondView] addConstraint: constraint];
Run Code Online (Sandbox Code Playgroud)

请注意:这里要记住,约束属性是在添加它们的视图的上下文中进行评估的.因此,例如,对于viewB上安装的约束,viewA的NSLayoutAttributeLeft的值在viewB的坐标空间中进行解释.对于仅引用同级视图或其超级视图的约束,该事实在很大程度上是不相关的,但是约束不能引用两个不是兄弟或直接父母的视图.


Mic*_*son 10

与neoneye类似,由于删除了带有约束的子视图,我得到了这个.但是我有一个约束定位父视图,如果我打电话,这个被删除[self.view removeConstraints:self.view.constraints];而是我做了这个改变,

原始代码:

for (UIView *subview in [view subviews]) {
    [subview removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)

已修复以删除子视图的约束:

NSMutableArray * constraints_to_remove = [ @[] mutableCopy] ;
for( NSLayoutConstraint * constraint in view.constraints) {
    if( [view.subviews containsObject:constraint.firstItem] ||
       [view.subviews containsObject:constraint.secondItem] ) {
        [constraints_to_remove addObject:constraint];
    }
}
[view removeConstraints:constraints_to_remove];

for (UIView *subview in [view subviews]) {
    [subview removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)

更新:所以我再次遇到这个错误 - 这是因为这次删除了一个视图.添加了一个干净地删除视图的功能:

void cleanRemoveFromSuperview( UIView * view ) {
  if(!view || !view.superview) return;

  //First remove any constraints on the superview
  NSMutableArray * constraints_to_remove = [NSMutableArray new];
  UIView * superview = view.superview;

  for( NSLayoutConstraint * constraint in superview.constraints) {
    if( constraint.firstItem == view ||constraint.secondItem == view ) {
      [constraints_to_remove addObject:constraint];
    }
  }
  [superview removeConstraints:constraints_to_remove];

  //Then remove the view itself.
  [view removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)