0

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

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

我得到的错误是

无法将“UIView”类型的值转换为预期的参数类型“[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
    }

我究竟做错了什么?在谷歌上找不到更多可以尝试的东西

4

1 回答 1

1

该错误告诉您需要一个. UIDynamicItem很容易错过小方括号。

你实际上是用(一个对象)而不是(一个数组)配置你的UIGravityBehaviorand 。这就是你得到错误的原因。UICollisionBehaviorredBoxView[redBoxView]


您需要将配置更改为此

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

和这个

collision = UICollisionBehavior (items: [redBoxView!]) //redBoxView passed in an array
于 2020-04-14T13:46:33.280 回答