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

后端 未结 7 1537
花落未央
花落未央 2020-12-09 16:05

Terminating app due to uncaught exception \'NSGenericException\'

Terminating app due to uncaught exception \'NSGenericException\', reason: \'Unable to

7条回答
  •  鱼传尺愫
    2020-12-09 16:16

    Similar to neoneye I was getting this due to removing subviews with constraints. However I had a constraint that was positioning the parent view, and this was being removed if I called [self.view removeConstraints:self.view.constraints]; Instead I made this change,

    Original Code:

    for (UIView *subview in [view subviews]) {
        [subview removeFromSuperview];
    }
    

    Fixed to remove constraints on subviews:

    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];
    }
    

    UPDATE: So I hit this error again - and it was due to removing a single view this time. Added a function to remove the view cleanly:

    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];
    }
    

提交回复
热议问题