为什么我的雪没有落到地上?

Why doesn't my snow fall to the ground?

我正在尝试制作一个应用程序(在 swift 中),背景是下雪。唯一的问题是我添加了重力动画,但是雪只是停留在原处。

这是我的代码:

ViewController.swift

import UIKit

@IBDesignable
class ViewController: UIViewController {

    @IBInspectable var BgColor:UIColor = UIColor.whiteColor()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = BgColor
        /*listSubviewsOfView(self.view)*/ /*Not needed to answer this*/
        var snow = Snow(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
        snow.opaque = false
        self.view.addSubview(snow)

        let animator = UIDynamicAnimator(referenceView: self.view)
        let gravity = UIGravityBehavior(items: [snow])
        let direction = CGVectorMake(0.0, 1.0)
        gravity.gravityDirection = direction
        animator.addBehavior(gravity)
        /*
        var snow = Snow(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
        snow.opaque = false
        snow.viewHeight = UIScreen.mainScreen().bounds.height
        snow.addSubview(snow)
        let animator = UIDynamicAnimator(referenceView: view)
        let gravity = UIGravityBehavior(items: [snow])
        animator.addBehavior(gravity)
*/
    }


    /*Not needed to solve this*/
    /*
    func listSubviewsOfView(views: UIView) {
        var index = 0
        let randomNumbers = [Int](1...24).shuffle()
        for view in views.subviews
        {
            if let _ = view.restorationIdentifier
            {
                view.setValue(String(Int(randomNumbers[index])), forKey: "updateText")
                index++
            }
            if index == randomNumbers.count {
                break
            }
        }
    }
    */

}

Snow.swift:

import Foundation
import UIKit

@IBDesignable
class Snow:UIView
{

    var viewHeight = CGFloat(0)
    /*
    required init(coder aDecoder: NSCoder) {
        //Initilse UIView
        super.init(coder: aDecoder)!
    }
    */

    override func drawRect(rect: CGRect) {
        let path = UIBezierPath(ovalInRect: rect)
        UIColor.whiteColor().setFill()
        path.fill()
    }
}

问题是,为什么我的雪在 (0,0) 处停留在屏幕上方而不是掉下来,即使我告诉它有重力影响?

创建视图控制器的 animatorgravity 属性。

import UIKit

@IBDesignable

class ViewController: UIViewController {

@IBInspectable var BgColor:UIColor = UIColor.whiteColor()

var animator: UIDynamicAnimator? = nil;
let gravity = UIGravityBehavior()

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.blackColor()

    let snow = Snow(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
    snow.opaque = false
    self.view.addSubview(snow)

    animator = UIDynamicAnimator(referenceView:self.view);
    animator?.addBehavior(gravity)

    gravity.addItem(snow)
    let direction = CGVectorMake(0.0, 1.0)
    gravity.gravityDirection = direction

    }
}