Ios 使用约束向目标移动按钮,无反应?
我希望红色按钮朝着第二个按钮的前导位置设置动画: 一些示例演示了如何用数字更改“常量”,但我想自动将其置于第二个按钮的前导位置 我尝试了这个,但是红色按钮没有移动,动画日志被正确调用:Ios 使用约束向目标移动按钮,无反应?,ios,objective-c,xcode,autolayout,constraints,Ios,Objective C,Xcode,Autolayout,Constraints,我希望红色按钮朝着第二个按钮的前导位置设置动画: 一些示例演示了如何用数字更改“常量”,但我想自动将其置于第二个按钮的前导位置 我尝试了这个,但是红色按钮没有移动,动画日志被正确调用: - (void)updateConstr{ NSLayoutConstraint *newLeading = [NSLayoutConstraint constraintWithItem:self.re
- (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];
}
在这种情况下,我通常会做以下几点 向场景中添加两个约束。在按钮和“一”标签之间左对齐的位置。第二个,在按钮和“第二个”标签之间向左对齐(即,两个值均为0)。这些约束最初会相互冲突,这很好 将
IBOutlets
添加到NSLayoutConstraints
的视图控制器中,并将我们创建的两个约束分配给那些IBOutlets
将初始条件的约束优先级设置为999(即左对齐到“一”的约束应为999)。将目标约束上的约束优先级设置为998(即,左对齐按钮“秒”上的约束优先级为998)。现在您将看到这些约束不再冲突。这是因为一个约束的优先级将覆盖另一个约束
你现在可以看到这一趋势了。因此,如果要在约束之间设置按钮动画,请交换优先级并设置动画
代码:
这必须做到:
- (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];
}];
}
非常感谢,如何添加新约束,而不修改故事板中的第一个约束?在底部有图标的情况下,无法选择“引导等的新约束”。啊,是的,通常在添加约束时,我只需控制两个元素之间的单击和拖动。因此,您可以控制+单击按钮并拖动到“秒”以添加新约束。然后选择约束并将其常量设置为0,并将两个元素的值设置为“前导”@Paul非常感谢Sandy,我使用了Ganesh代码的微小差异,但我会记住您的解决方案!非常感谢你的邀请answers@Paul很高兴你让它工作了。我的解决方案的一个优点是没有硬编码的值。IB中的所有内容都是可修改的,所以您不必在代码中搜索幻数进行更新。
- (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];
}];
}