我正在尝试在 iOS swift 中制作一些动画,但无法让重力正常工作,这是我的代码,红色框只是保持不动

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

引力似乎没有任何作用,只是不知道如何让它发挥作用。这是我的代码,红色框只是保持不动。任何帮助将不胜感激 导入 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)

    }
}

问题是您的 UIDynamicAnimator animate 被声明为局部变量。因此它出现并再次消失,没有时间激活任何东西。改为将其声明为实例变量。