我想构建一个简单的自定义视图,它使用 UIDynamicAnimator 从底部向上滑动。
当应用程序加载时,我使用以下方法从屏幕上偏移视图:
panelWidth = originView!.frame.size.width
panelHeight = originView!.frame.size.height/2
screenHeight = originView!.frame.size.height
// Set the frame for the container of this view based on the parent
container.frame = CGRectMake(0, screenHeight, panelWidth, panelHeight)
为了设想这一点,我希望视图显示为:
|-----|
| |
| A | <--- Main View
| |
|-----|
|-----|
| B | <--- Second View (offset by screen height so it draws directly under (0,height))
|-----|
我已经设置了手势识别器来检测我何时向上和向下滑动(向上显示,向下关闭),但是现在视图从屏幕上反弹,我似乎永远无法恢复。
使用我的动画师,我使用以下代码
animator.removeAllBehaviors()
isOpen = open
let gravityY:CGFloat = (open) ? -0.5 : 0.5
let gravityX:CGFloat = 0
let magnitude:CGFloat = (open) ? -20 : 20
let boundaryY:CGFloat = (open) ? -panelHeight : panelHeight
let boundaryX:CGFloat = (open) ? 0 : 0
在展示其余代码之前,我想我应该讨论一下我的常量。矢量数学不是我的强项,所以这可能是所有这一切都出错的唯一原因。我将值设置为负值,open
因为我想将视图动画返回到屏幕上,这意味着向上动画,因此我假设我需要负重力。
我将boundaryY设置为面板的高度,因为我只想将它动画到屏幕上到窗口的高度,目前它飞离顶部(当我调试屏幕高度= 667和panelHeight = 333.5所以我不'不明白为什么它超过了那个标记)
// animator behaviours - here I just create animaters on the panels container
let gravityBehaviour:UIGravityBehavior = UIGravityBehavior(items: [container])
let collisionBehaviour:UICollisionBehavior = UICollisionBehavior(items: [container])
let pushBehaviour:UIPushBehavior = UIPushBehavior(items: [container], mode: UIPushBehaviorMode.Instantaneous)
let panelBehaviour:UIDynamicItemBehavior = UIDynamicItemBehavior(items:[container])
// Gravity behaviour - I don't want it to move in X direction, only Y
gravityBehaviour.gravityDirection = CGVectorMake(gravityX, gravityY)
// collision detection - I think this is the major problem, how does this work...
collisionBehaviour.addBoundaryWithIdentifier("basePanelBoundary", fromPoint: CGPointMake(boundaryX, 0), toPoint: CGPointMake(boundaryX, boundaryY))
// push behaviours
pushBehaviour.magnitude = magnitude
// panel behaviours
panelBehaviour.elasticity = 0.3
// bind behaviours
animator.addBehavior(gravityBehaviour)
animator.addBehavior(collisionBehaviour)
animator.addBehavior(pushBehaviour)
animator.addBehavior(panelBehaviour)
我主要关心碰撞检测,因为我相信这是导致视图旋转并从屏幕上飞出的原因,我该如何解决这个问题?