How do I let objects fall in swift?

Hey guys, im currently working on my first app and my first problem is that I have an image that I want to fall down. Can anyone explain to me how I do that? Thanks!

It depends a lot on what frameworks you are using, for example SpriteKit includes things explicitly to help you make things move around.

If just UIView based then you probably want to put the view in place with a constraint which you can then alter. Let’s say you anchor the view to something above it with a constraint and the constant is 0 because they are right next to each other - top of the falling view to the bottom of the anchoring view. To make it fall you set that constant to something larger and then animate the constraint change with a simple block:

            UIView.animate(withDuration: 0.6, animations: {
                self.view.layoutIfNeeded()
            })

This makes the constraint change happen over the period of 0.6 seconds, making the view “fall”.

There’s a lot to this subject so check out the cool tutorial by Marin Todorov, right here.

1 Like