ios - 使用 UIDynamics 重力为 CGRects 设置动画

标签 ios swift uikit uikit-dynamics

我的目标是让一堆具有 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()

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

最佳答案

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

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

删除盒子变量,然后

改变:

func addBox(location: CGRect) 

到:

func addBox(location: CGRect) -> UIView

并且 在最后返回 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 中你不需要分号)

关于ios - 使用 UIDynamics 重力为 CGRects 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098987/

相关文章:

swift - 用于对象识别的 ARKit 和 Vision 框架

ios - swift 3 : Tableview datasource methods "Overriding non-open instance method outside of its defining module" error

ios - 如何让我的 UIButton 标题有一些填充?

objective-c - 没有子类化 UIView 或 UIViewController : possible to catch if a subview was added?

iphone - RestKit 0.20使用nsdata发布数组Json

ios - 未从 VideoPreviewLayer 调用 attemptsBegan 方法

ios - TRON 快速响应头

ios - 在 Swift 的自定义 UIView 子类中通过 UIAppearance 设置文本属性

ios - 在 Swift 中检查 iOS 设备是否有 LiDAR

iOS:上传图片到服务器,打不开