我定义了UIDynamicAnimator属性:
lazy fileprivate var animator: UIDynamicAnimator = {
return UIDynamicAnimator(referenceView: self)
}()
self是UIView的子类;
在自我类的扩展中,同一个文件,我有动画的逻辑,使用我的动画师,添加了UIDynamicBehavior项目:
let pushBehavior = UIPushBehavior(items: [stampView], mode: .continuous)
//some settings
let dynamicItemBehavior = UIDynamicItemBehavior(items: [stampView])
//some settings
let gravityBehavior = UIGravityBehavior(items: [stampView])
//some settings
let collisionBehavior = UICollisionBehavior(items: [stampView])
//some settings
一切正常,但当我尝试使用removeAllBehaviors()动画停止所有动画时停止,但行为仍然在animator.behaviors中。我第二次调用它时,数组变空了。
// ==
对于我的pushBehavior,我添加了一个动作,它改变了var,表示我达到了目标点:
pushBehavior.action = { [unowned stampView] in
if stampView.center.x <= endPosition.x {
lastJump = true
}
}
在collisionBehavior委托方法中,我检查此变量并尝试使用removeAllBehaviors()
停止动画public func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
if lastJump {
//animator.behaviors.count = 4
animator.removeAllBehaviors()
//still, animator.behaviors.count = 4
}
}
答案 0 :(得分:1)
你说你正在测试这样:
public func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
if lastJump {
//animator.behaviors.count = 4
animator.removeAllBehaviors()
//still, animator.behaviors.count = 4
}
}
好吧,animator.removeAllBehaviors()
是一个 em>包括你的代码正好在的中间。如果行为真的在那一刻停止了,我们甚至都不会到达你代码的下一行!
因此,动画师在代码停止运行后(也称为运行循环结束)之前,实际上不会删除行为。
解决此问题的方法是等到在之后代码停止,然后再调用removeAllBehaviors()
。您可以使用我的delay
实用程序(https://stackoverflow.com/a/24318861/341994)轻松完成此操作:
public func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
if lastJump {
delay(0.1) {
animator.removeAllBehaviors()
}
}
}