如果您只是想从层次结构中删除视图,只需调用[theView removeFromSuperview]。任何影响它的约束也将被删除。
但是,有时您可能还希望在 暂时 移除视图后将其放回原处。
为了实现这一点,我在UIView 上使用了以下类别。它将视图层次结构从视图v 向上移动到一些最终的容器视图c(通常是您的视图控制器的根视图)并删除v 外部的约束。这些是与v 同级的约束,而不是仅影响v 的子级的约束。你可以隐藏v。
-(NSArray*) stealExternalConstraintsUpToView: (UIView*) superview
{
NSMutableArray *const constraints = [NSMutableArray new];
UIView *searchView = self;
while(searchView.superview && searchView!= superview)
{
searchView = searchView.superview;
NSArray *const affectingConstraints =
[searchView.constraints filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(NSLayoutConstraint *constraint, NSDictionary *bindings)
{
return constraint.firstItem == self || constraint.secondItem == self;
}]];
[searchView removeConstraints: affectingConstraints];
[constraints addObjectsFromArray: affectingConstraints];
}
return constraints;
}
该方法将删除的约束传递回一个数组中,您可以将其保留在某个地方,以便稍后您可以添加回约束。
使用它有点像这样......
NSArray *const removedConstraints = [viewToHide stealExternalConstraintsUpToView: self.view];
[viewToHide setHidden: YES];
稍后,将约束放回去。
从 iOS 8 开始,您无需考虑应该将约束放在哪里。就用这个……
[NSLayoutConstraint activateConstraints: removedConstraints];
[viewToHide setHidden: NO];
使用早期版本的 iOS,您无需费力考虑在何处添加约束。然后扔进控制器的self.view。如果约束在它们影响的所有视图的一个超级视图中,它们就会起作用。
[self.view addConstraints: removedConstraints];
[viewToHide setHidden: NO];