简体   繁体   中英

“Launch” and drop a UIView

在此输入图像描述

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM