【问题标题】:Swift UIImage cant be animated with gravitySwift UIImage 不能用重力动画
【发布时间】:2020-02-23 21:44:58
【问题描述】:

我在 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
    }

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

【问题讨论】:

    标签: swift uianimation uikit-dynamics uidynamicanimator


    【解决方案1】:

    错误表明您需要一个UIDynamicItem数组。很容易错过小方括号。

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


    你需要把你的配置改成这个

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

    还有这个

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

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多