【发布时间】:2020-10-21 14:09:44
【问题描述】:
我正在 iOS 上制作一个有很多动画的纸牌游戏。有时当两个动画同时发生时,动画卡片会弹回其原始位置。我发现这是因为我为 UIView 的中心而不是它的约束设置了动画。现在,我正在尝试使用其约束为卡片设置动画。该卡必须动画到另一张卡的顶部。我想知道是否有办法将一个 UIView 的所有约束复制到另一个 UIView 的约束?
我试过了
newConstraints = object1.constraints
object2.addConstraints(newConstraints)
然后动画它,但它没有工作。
我使用以下代码移动卡片:
private func replaceConstraints(_ superview: UIView, ofView view1: AnyObject, toView view2: AnyObject) -> [NSLayoutConstraint]{
var constraintsToRemove: [NSLayoutConstraint] = []
var constraintsNew_item1: [NSLayoutConstraint] = []
for constraint in superview.constraints
{
if (constraint.firstItem === view1)
{
constraintsToRemove.append(constraint)
constraintsNew_item1.append(NSLayoutConstraint(item: view2, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant))
}
}
superview.removeConstraints(constraintsToRemove);
superview.addConstraints(constraintsNew_item1);
return constraintsToRemove
}
后跟:self.view.layoutIfNeeded()
卡片确实动画到了所需的位置,但它应该放在上面的卡片从它的位置移动了一点,给了我以下警告:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x6000030aaa80 UIView:0x7f8f8870af50.centerY == 0.5*UIView:0x7f8f8870b0c0.centerY (active)>",
"<NSLayoutConstraint:0x6000030a7e80 UIView:0x7f8f8870af50.centerY == 1.5*UIView:0x7f8f8870b0c0.centerY (active)>",
"<NSLayoutConstraint:0x6000030baf80 'UIView-Encapsulated-Layout-Height' UIView:0x7f8f8870b0c0.height == 667 (active)>"
)
另外,我的大部分动画都是在 CardView 类中制作的,所以我想知道是否有动态的方法。
谢谢。
【问题讨论】:
标签: ios swift uiview constraints core-animation