So I am trying to add gravity to 4 UIButtons but they are not falling, I added this code to the view did load, I don't why this isn't working well. Here is the code:
//initialize the animator
var animator = UIDynamicAnimator(referenceView: self.view)
//add gravity
let gravity = UIGravityBehavior(items: [redButton!, greenButton!, blueButton!, cameraButton!])
let direction = CGVectorMake(0.0, 1.0)
gravity.gravityDirection = direction
animator.addBehavior(gravity)
My buttons are the redButton, greenButton, blueButton, and the cameraButton, also I have applied the direction of the fall but when I run the app they are just static. So is it possible to add gravity to the UIButtons?
You are declaring your animator locally to the function. When the function returns, the animator is released from memory, and all animation stops (actually viewDidLoad()
returns so early in the lifecycle that animation never gets started).
Declare it as:
var animator: UIDynamicAnimator!
at class scope
Class scope means put it within the curly braces of the class:
class Foo {
var thisVariableIsAtClassScopeAndPersistsAcrossMethods: Int
func bar() {
var thisVariableIsAtLocalScopeAndDisappearsWhenFunctionReturns: String
}
}
And only initialize it in viewDidLoad()
:
animator = UIDynamicAnimator(referenceView: self.view)
(You cannot initialize it at class scope without lazy
trickiness, because self
is not yet available.)
** EDIT FINAL ANSWER **
After chat, we resolved the misunderstood answer and now we have:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var redButton: UIButton!
@IBOutlet weak var greenButton: UIButton!
@IBOutlet weak var blueButton: UIButton!
@IBOutlet weak var cameraButton: UIButton!
// Declare the animator at class scope so it doesn't get released prematurely.
var animator: UIDynamicAnimator!
override func viewDidLoad() {
super.viewDidLoad()
//add gravity
let gravity = UIGravityBehavior(items: [redButton, greenButton, blueButton, cameraButton])
let direction = CGVectorMake(0.0, 1.0)
gravity.gravityDirection = direction
animator.addBehavior(gravity)
// other viewDidLoad setup code to set attributes of buttons
}
}