How to make several UIImages simultaneously fall with gravity?

As a user types a supervisor, I discover it through UITapGestureRecognizerand calling the function below to create a view UIImage, add it to the supervisor, add gravity to it and let it drop out of the supervisor.

The problem is that if the user picks up again when the first UIImageis still on the screen, the first image stops in place and the second UIImagestarts to fall. What is the best way to make several UIImagefall independently on the screen.

Secondly, I feel that I have to remove these UIImagefrom the supervisor to save memory (since there may be hundreds of taps, but I can’t figure out how to automatically delete UIImageas soon as it leaves the screen.

Help fast.

func dropBall(tapLocation:CGPoint) {
    let ball = UIImageView(image: UIImage(named: "White50.png"))
    ball.frame = CGRect(origin: CGPoint(x:tapLocation.x-25,y:tapLocation.y-25), size: CGSize(width:50,height:50))
    view.addSubview(ball)

    animator = UIDynamicAnimator(referenceView: self.view)
    gravity = UIGravityBehavior(items: [ball])
    animator.addBehavior(gravity)
}
+4
source share
1 answer

The reason the first animation stops is that when you call it again, you create a new animator and release the old one. You must create an instance of the animator only once. Likewise, you must instantly create gravity.

, , action , , , , .

override func viewDidLoad() {
   super.viewDidLoad()

    animator = UIDynamicAnimator(referenceView: view)

    gravity = UIGravityBehavior()
    gravity.action = { [unowned self] in
        let itemsToRemove = self.gravity.items.filter() { !CGRectIntersectsRect(self.view.bounds, $0.frame) }
        for item in itemsToRemove {
            self.gravity.removeItem(item as UIDynamicItem)
            item.removeFromSuperview()
        }
    }
    animator.addBehavior(gravity)
}

, , , , :

gravity.addItem(ball)
+7

Source: https://habr.com/ru/post/1569055/


All Articles