swiftuidynamicanimatoruigravitybehavior

I'm trying to do some animation in iOS swift and Not able to get the gravity working , here is my code the red box just stays with out moving


The gravity doesn't seem to do anything , just can't figure out how to get it to work. here is my code the red box just stays with out moving .any help would be appreciated import UIKit

class ViewController: UIViewController {
    var box : UIView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
            addBox(CGRectMake(100, 100, 30, 30))
        createAnimation()


        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func addBox(location: CGRect) {
        let newBox = UIView(frame: location)
        newBox.backgroundColor = UIColor.redColor()

        view.insertSubview(newBox, atIndex: 0)
        box = newBox

    }

    func createAnimation(){
        var animate = UIDynamicAnimator(referenceView: self.view)
        println("animation")
        var gravity = UIGravityBehavior(items: [box])

        gravity.gravityDirection = CGVectorMake(0, 0.6)
        animate.addBehavior(gravity)

    }
}

Solution

  • The problem is that animate, your UIDynamicAnimator, is declared as a local variable. Thus it comes into existence and goes right back out of existence again, with no time to animate anything. Declare it as an instance variable instead.