Search code examples
iosswiftuikit

make UIImageView fall


I've UIImageview with its own position, after clicking that ( done with tapgesture ) I want that view to fall to ground until the position is 0. I tried making it with while loop but doesn't seem to work. any soltuions ?

    var bananaView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

    @objc func handleTap(_ sender:UITapGestureRecognizer) {
        let centerPosition = bananaView.frame.origin.y
        while centerPosition >= 0 {
            bananaView.layer.position = CGPoint(x: 0,y : centerPosition - 1)
        }
    }

Solution

  • You set the new position (0) for it. Then you wrap the layout update inside an animation block

    @objc func handleTap(_ sender:UITapGestureRecognizer) {
        let centerPosition = bananaView.frame.origin.y
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
            if bananaView.frame.origin.y - bananaView.frame.height == 0 {
                timer.invalidate()
            } else {
                bananaView.frame.origin.y -= 1
            }
        }
    }