使用UIDynamics引力为CGRects制作动画

时间:2017-03-29 16:19:54

标签: ios swift uikit uikit-dynamics

我的目标是让一堆UIViews具有CGRect属性从屏幕外掉落然后堆积起来。现在,我有一个圆圈工作,但每次我尝试添加另一个圆圈时,它们将不再动画。我正在使用UIDynamics及其gravity函数。这是我的代码:

func addBox(location: CGRect) -> UIView {
    let newBox = UIView(frame: location)
    newBox.backgroundColor = UIColor(red: 186.0/255.0, green: 216.0/255.0, blue: 242.0/255.0, alpha: 1.0)
    newBox.layer.cornerRadius = newBox.frame.width/2

    hView.insertSubview(newBox, at: 0)

    return newBox
}


addBox(location: CGRect(x: 100, y: -100, width: 100, height: 100))    

var animator: UIDynamicAnimator? = nil;
let gravity = UIGravityBehavior()
var collision: UICollisionBehavior!
animator = UIDynamicAnimator(referenceView: hView)

func createAnimatorStuff(box: UIView) {
    collision = UICollisionBehavior(items: [box])
    collision.translatesReferenceBoundsIntoBoundary = true
    animator?.addBehavior(collision)

    gravity.addItem(box)
    gravity.gravityDirection = CGVector(dx: 0, dy: 0.8)
    animator?.addBehavior(gravity)

}

func dropDown() {
    let xVal = 100
    let xVal2 = 700

    let box = addBox(location: CGRect(x: xVal, y: 100, width: 100, height: 100))
    let box2 = addBox(location: CGRect(x: xVal2, y: 100, width: 100, height: 100))
    createAnimatorStuff(box: box)
    createAnimatorStuff(box: box2)
}
dropDown()

如果有人可以帮助我并调整我的代码以创建更多的圆圈,然后堆积起来我会非常感激它。真正做到。请提出任何问题,并提前感谢您。

1 个答案:

答案 0 :(得分:1)

(注意:问题已根据这些建议进行了更新,因此它似乎表明了已经完成的事情)

您遇到的一般问题是,您将box设为全局变量并继续重新初始化UIDynamicAnimator。所以...

删除框var,然后

变化:

func addBox(location: CGRect) 

为:

func addBox(location: CGRect) -> UIView

return newBox在最后。

然后,改变:

func createAnimatorStuff() {

为:

func createAnimatorStuff(box: UIView) {

addBox(location: CGRect(x: xVal, y: 100, width: 100, height: 100))
createAnimatorStuff()

let box = addBox(location: CGRect(x: xVal, y: 100, width: 100, height: 100))
createAnimatorStuff(box: box)

最后,不要为每次通话创建一个新的UIDynamicAnimator - 制作一个并分享它。您可以使用

执行此操作
let animator = UIDynamicAnimator(referenceView: hView)

(另外,你不需要在Swift中使用分号)