“Launch” and drop a UIView

萝らか妹 提交于 2019-12-06 13:52:05

问题


Above picture illustrates what I want:

  • The red circle is the starting point of a UIView
  • I want to launch it upwards (Y position) with a change in the X position
  • I want to make it drop within boundaries.

What I tried:

For the launch I can make use of the UIView.animate function. For the drop I can use the UIDynamicAnimator. However there are some problems:

-In the UIView.animate I cannot 'curve' the animation, only a straight line. I can use this answer here to draw a curve line: https://stackoverflow.com/a/43813458/7715250

-Combining both functions is not working. After the UIView.animate is done, the UIView just drop straight downwards.

The code for UIDynamicAnimator:

var animator: UIDynamicAnimator!

    //view did appear
    let view2 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    view2.center = self.view.center
    view2.backgroundColor = .blue
    self.view.addSubview(view2)
    animator = UIDynamicAnimator(referenceView: self.view)
    let gravity = UIGravityBehavior(items: [view2])
    animator.addBehavior(gravity)
    let collosion = UICollisionBehavior(items: [view2])
    collosion.translatesReferenceBoundsIntoBoundary = true
    let dynamic = UIDynamicItemBehavior(items: [view2])
    dynamic.elasticity = 0.7
    animator.addBehavior(collosion)
    animator.addBehavior(dynamic)

That will drop the UIView with a nice bounce effect. But how to launch the UIView? How to change the X and Y position and remain the added behaviours?


回答1:


I think what you need is UIPushBehavior. Add this extra behavior.

let push = UIPushBehavior(items: [view2], mode: UIPushBehaviorMode.instantaneous)
push.setAngle(CGFloat(-M_PI/2 - 0.1), magnitude: 8.0) // Adjust angle and magnitude
animator.addBehavior(push)


来源:https://stackoverflow.com/questions/45921609/launch-and-drop-a-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!