iOS:Autolayout:动画后锁定新位置

时间:2013-12-07 22:45:24

标签: ios objective-c cocoa-touch autolayout nslayoutconstraint

我尝试为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];

1 个答案:

答案 0 :(得分:0)

来自layoutSubviews的文档:

  

您不应直接调用此方法。

改为呼叫layoutIfNeeded