移动button朝目标使用约束,没有反应?

我想让红色button朝着第二个button的主导位置animation:

在这里输入图像说明

一些例子说明了如何用数字来改变“常量”,但是我想自动地把第二个button的主导位置。

我试过这个,但红色的button不动,animation日志被正确调用,虽然:

- (void)updateConstr{ NSLayoutConstraint *newLeading = [NSLayoutConstraint constraintWithItem:self.redB attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.secondButton attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f]; self.leadingConstraint = newLeading;//is an IBOutlet pointing on the constraint (see the image) [self.redB setNeedsUpdateConstraints]; [UIView animateWithDuration:0.5 animations:^{ [self.redB layoutIfNeeded]; NSLog(@"animations");//is called, but the red button does not move }]; } - (IBAction)firstAction:(id)sender { //after a click on button "one" NSLog(@"firstAction"); [self updateConstr]; } 

这必须做到这一点:

 - (void)updateConstr{ NSLayoutConstraint *newLeading = [NSLayoutConstraint constraintWithItem:self.redB attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.secondButton attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f]; [self.redB.superview removeConstraint: self.leadingConstraint]; [self.redB.superview addConstraint: newLeading]; self.leadingConstraint = newLeading; [UIView animateWithDuration:0.5 animations:^{ [self.redB layoutIfNeeded]; }]; } 

我通常在这种情况下做的是以下几点。

在场景中添加两个约束。 在button和“one”标签之间alignment的地方。 第二个,它在button和“第二个”标签之间左alignment(即两个值都是0)。 这些约束最初会相互冲突,没关系。

IBOutlets添加到NSLayoutConstraints视图控制器中, NSLayoutConstraints我们创build的两个约束分配给这些IBOutlets

将您的初始条件的约束优先级设置为999(即,左alignment到“1”的约束应该是999)。 将目标约束上的约束优先级设置为998(即,button与“秒”之间左alignment的约束是998)。 您现在将会看到这些限制不会再发生冲突。 这是因为一个约束的优先级会覆盖另一个约束。

你现在可以看到这个方向。 所以,当你想在约束之间animationbutton时,交换优先级和animation!

码:

 @interface MyViewController () @property (nonatomic, weak) NSLayoutConstraint* constraint0; @property (nonatomic, weak) NSLayoutConstraint* constraint1; @end - (void)someMethodWhereIWantToAnimate { NSInteger temp = constraint0.priority; constraint0.priority = constraint1.priority; constraint1.priority = temp; [UIView animateWithDuration:1.0 animations:^{ // Simplest is to use the main ViewController's view [self.view layoutIfNeeded]; }]; }