我尝试为UIView编写一个类别函数,它将获得将在其superview中保存给定框架的约束。我这样实现了它:
-(NSArray *)constraintsForLockingPositionInSuperview
{
NSLayoutConstraint *left=[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.superview
attribute:NSLayoutAttributeLeft multiplier:0 constant:self.frame.origin.x];
NSLayoutConstraint *height=[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:Nil
attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:self.frame.size.height];
NSLayoutConstraint *width=[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:Nil
attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:self.frame.size.width];
NSLayoutConstraint *top=[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.superview
attribute:NSLayoutAttributeTop multiplier:0 constant:self.frame.origin.y];
return @[left,height,width,top ];
}
然后在为视图设置动画后,通过在包含相关视图的视图控制器中执行以下操作来应用新约束。我删除视图然后重新添加它以删除其上的约束,然后重新应用新约束。希望如果我添加另一个子视图或者像actionView这样的东西进入并且视图必须自行布局,这将保持视图到位。高度和宽度似乎正确锁定,但视图跳到中间而不是锁定到位:
NSArray *lockingConstraints = [someView constraintsForLockingPositionInSuperview];
[someView removeFromSuperview];
[self.view addSubview:someView;
[self.view addConstraints:lockingConstraints];
[self.view layoutSubviews];