1
votes

I'm attempting to convert the Ray Wenderlich's tutorial on UIDynamics to swift code, but I'm stuck on the very first part.

http://www.raywenderlich.com/50197/uikit-dynamics-tutorial

Here's what I'm doing:

  1. created a square UIView
  2. added a UIDynamicAnimator to the main view
  3. added a UIGravityBehavior and initialized it with the square
  4. added gravity behavior to the animator

It all compiles and runs fine but the square doesn't move. Can anybody see what I'm doing wrong?

https://github.com/oisinlavery/UIDynamics-Swift

1

1 Answers

4
votes

You've created your animator as a local variable to your go method, so it disappears as soon as that method is finished. It needs to be an instance variable on your ViewController class so that it will stick around and do the work of animating the square:

class ViewController: UIViewController {
    var animator: UIDynamicAnimator?

    @IBAction func go(sender : UIButton) {
        var square = UIView(frame: CGRectMake(100, 100, 100, 100))
        square.backgroundColor = UIColor.blackColor()
        self.view.addSubview(square)

        self.animator = UIDynamicAnimator(referenceView: self.view)
        var grav = UIGravityBehavior(items:[square])

        self.animator!.addBehavior(grav)
    }
}