Swift UIImage 无法使用重力动画

Swift UIImage cant be animated with gravity

我已经查看了 Google 上的所有内容,但并不多。 Swift的社区真的这么小吗???

我有一个图像,在长按时,我希望它在重力作用下掉落并撞到屏幕底部。

我得到的错误是

Cannot convert value of type 'UIView' to expected argument type '[UIDynamicItem]'

我已经尝试过 UILabel、UIImage、UIImageView、Rect、UIView,但无论我做什么,都会遇到此错误。 我的目标是使用 UIImage 或 UIImageView。


这是我用于动画的代码:

    var animator: UIDynamicAnimator!
    var gravity: UIDynamicBehavior!
    var collision : UICollisionBehavior!

    var redBoxView: UIView?
    @IBOutlet weak var detailsImageWeather: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        animator = UIDynamicAnimator(referenceView: self.view)
        let imageTap = UILongPressGestureRecognizer(target: self, action: #selector(imageTapped))
        detailsImageWeather.addGestureRecognizer(imageTap)
    }

    @objc func imageTapped() {
        var frameRect = CGRect(x: 150, y: 20, width: 60, height: 60)
        redBoxView = UIView(frame: frameRect)
        redBoxView?.backgroundColor = UIColor.red
        self.view.addSubview(redBoxView!)

        let image = detailsImageWeather.image // This is what i want to use instead of redBoxView
        gravity = UIGravityBehavior(items: redBoxView!)
        animator.addBehavior(gravity)

        collision = UICollisionBehavior (items: redBoxView!)
        collision.translatesReferenceBoundsIntoBoundary = true
        animator.addBehavior(collision)

        let behavior = UIDynamicItemBehavior(items: [redBoxView!])
        behavior.elasticity = 2
    }

我做错了什么?找不到更多可以尝试的东西 google

错误

Cannot convert value of type 'UIView' to expected argument type '[UIDynamicItem]'

表示您需要 数组 UIDynamicItem。很容易漏掉小方括号。

您实际上是在使用 redBoxView(对象)而不是 [redBoxView](数组)配置 UIGravityBehaviorUICollisionBehavior。这就是您收到错误的原因。


您需要将配置更改为此

gravity = UIGravityBehavior(items: [redBoxView!]) //redBoxView passed in an array

还有这个

collision = UICollisionBehavior (items: [redBoxView!]) //redBoxView passed in an array