所以我试图将重力添加到4个UIButton,但它们没有下降,我将这个代码添加到视图中,但是我不知道为什么它不能正常工作。 这是代码:
//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)
我的按钮是redButton,greenButton,blueButton和cameraButton,我也应用了秋天的方向但是当我运行应用程序时它们只是静态的。那么是否有可能将重力添加到UIButtons?
答案 0 :(得分:4)
您正在本地声明您的动画师。当函数返回时,动画师从内存中释放,并且所有动画都停止(实际上viewDidLoad()
在动画永远不会开始的生命周期的早期返回)。
声明为:
var animator: UIDynamicAnimator!
在 class 范围
类范围意味着将它放在类的花括号中:
class Foo {
var thisVariableIsAtClassScopeAndPersistsAcrossMethods: Int
func bar() {
var thisVariableIsAtLocalScopeAndDisappearsWhenFunctionReturns: String
}
}
仅在viewDidLoad()
中初始化:
animator = UIDynamicAnimator(referenceView: self.view)
(你不能在没有lazy
棘手的情况下在课程范围内初始化它,因为self
尚未可用。)
**编辑最终答案**
聊天后,我们解决了误解的答案,现在我们已经:
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
}
}