簡體   English   中英

UIDynamicAnimator,removeAllBehaviors()第一次不起作用

[英]UIDynamicAnimator, removeAllBehaviors() doesn't work at first time

我定義了UIDynamicAnimator屬性:

lazy fileprivate var animator: UIDynamicAnimator = {
        return UIDynamicAnimator(referenceView: self)
}()

self是UIView的子類;

在self class的擴展中,同一文件中,我具有動畫邏輯,該動畫使用我的動畫師,並添加了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
    }
}

您說您正在像這樣進行測試:

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()是一個應該刪除行為的命令,但是現在不能遵守該命令,因為這些行為仍在起作用, 包括您的代碼在中間的正確行為 如果這些行為在那一刻才真正停止,那么我們甚至都不會到達您的代碼的下一行!

因此,動畫設計師實際上並不會刪除行為,直到您的代碼停止運行之后 (也稱為運行循環結束)。

該方法可以解決這個要等到你的代碼調用之前停止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()
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM