设置后NSLayoutConstraint常量不更新

我有一个UIView子类与相应的xib文件。 在我的xib中,我有一个NSLayoutConstraint属性,我正在尝试动画。 我有一个animateIn方法。 问题是只有animateIn方法有效。 当我尝试再次更新常量时,它只是保持在前一个值。

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *horizontalConstraint; 

按下按钮后,我正在尝试更新常量。 但是这个常数在设置后似乎没有更新。 即使将其设置为-500后,它仍然会记录0。 我正在调用layoutIfNeeded但没有任何反应。

 // this works - (void) animateIn { [UIView animateWithDuration:1.0 delay:2.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.alpha = 1.0; } completion:^(BOOL finished) { [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.horizontalConstraint.constant = 0; [self layoutIfNeeded]; } completion:^(BOOL finished) { }]; }]; } // this does not work - (IBAction)resume:(id)sender { self.horizontalConstraint.constant = -500; [self layoutIfNeeded]; NSLog(@"%f",self.horizontalConstraint.constant); // this always stays 0 } 

UPDATE

当我想第二次使用它时,我的NSLayoutConstraint似乎是(null)。 这可以解释为什么它没有更新。 我该如何保留它的参考?

您需要调用setNeedsUpdateConstraints所在的相应UIView(control)setNeedsUpdateConstraints方法来更新约束。

例如UIButton

 self.buttonConstraint.constant = 55; [self.btnTest setNeedsUpdateConstraints]; 

在你的情况下

 [self setNeedsUpdateConstraints]; 

你确定这个约束在某个地方没有被激活吗? 将约束的“active”属性设置为false会导致视图层次结构删除约束。 如果您还没有对它的引用,则约束对象将从内存中删除。

我和你有同样的问题,并删除了“弱”,因此约束现在是一个强大的属性。 因此,在取消激活时它不会设置为nil(因为我的视图控制器总是有一个强指针),我可以重新激活它并重新设置它的常量。

 // NB: don't create these contraints outlets as "weak" if you intend to de-activate them, otherwise they would be set to nil when deactivated! @IBOutlet private var captionViewHeightConstraint: NSLayoutConstraint! 

完成约束更改后,只需调用:

 [self setNeedsUpdateConstraints]; 

我遇到了一个问题,我第一次在代码中设置约束常量将设置常量,但之后调用layoutIfNeeded(),如下所示:

 myConstraint.constant = newValue; [view layoutIfNeeded] 

常数会回到原始值! 我可以在调试器中看到值的变化。

我终于想通了,因为在故事板中,我已经设定了常数的变化。 例如:

在此处输入图像描述

一旦删除了变体,约束常量值就不会通过layoutIfNeeded调用变回原始值。

horizo​​ntalConstraint属性应该由视图本身保存。 只要视图处于活动状态,属性就不应该为nil(除非您在代码中的其他位置将其设置为nil)。 仔细检查是否将其设置为nil。