【问题标题】:Using UIDynamics gravity to animate CGRects使用 UIDynamics 重力为 CGRects 设置动画
【发布时间】:2017-03-29 16:19:54
【问题描述】:

我的目标是让一组具有CGRect 属性的UIViews 从屏幕外掉下来然后堆积起来。现在,我有一个圈子在工作,但每次我尝试添加另一个圈子时,它们就不再有动画了。我正在使用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()

如果有人可以帮助我并调整我的代码以创建更多的圆圈下降然后堆积,我将非常感激。真的。请提出任何问题,并在此先感谢您。

【问题讨论】:

    标签: ios swift uikit uikit-dynamics


    【解决方案1】:

    (注意:问题已根据这些建议进行了更新,这就是为什么它似乎建议已经完成的事情)

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

    删除box 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 中你不需要分号)

    【讨论】:

    • 非常感谢!它就像平常一样工作,但我将如何添加另一个盒子。我尝试在dropDown 中添加一个,但它停止了所有动画。我做另一个功能吗?定义一个新的addBox?
    • 您应该发布您的新代码作为对问题的编辑。
    • 刚刚做到了!抱歉,我一开始就应该这样做
    • 您没有按照我的建议删除 animator = UIDynamicAnimator(referenceView: hView);。在函数之外对其进行初始化,使其只执行一次。
    • 这是在游乐场吗?如果是这样,您使用的是 liveView 吗?如果是这样,您是否还设置了 needsIndefiniteExecution?
    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2015-11-22
    相关资源
    最近更新 更多