2016-09-17 32 views
0

我尝试构建类似于界面的类似视图,并且我希望视图在弹出手指时以弹跳方式捕捉到父视图的中心。我试图用快速行为和平移手势识别器来实现它,但是我发现我看到了下降视图的动画。UIKit动态 - 快照视图到父视图的中心

enter image description here

我的代码如下

class ViewController: UIViewController { 

var d = UIView() 
var snap: UISnapBehavior! 
var animator:UIDynamicAnimator! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    d.translatesAutoresizingMaskIntoConstraints = false 
    d.backgroundColor = .redColor() 

    view.addSubview(d) 

    d.heightAnchor.constraintEqualToConstant(150).active = true 
    d.widthAnchor.constraintEqualToConstant(150).active = true 
    d.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true 
    d.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true 

    d.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "pan:")) 

    animator = UIDynamicAnimator(referenceView: d) 


} 

func pan(gesture:UIPanGestureRecognizer) { 
    switch gesture.state { 
    case .Changed: 
     d.frame.origin.x = gesture.translationInView(d).x 
    case .Ended: 
     snap = UISnapBehavior(item: d, snapToPoint: view.center) 
     animator.addBehavior(snap) 
    default: 
     break 
    } 
} 
} 

回答

0

你应该设置的UIDynamicAnimator的referenceView查看和不d。

animator = UIDynamicAnimator(referenceView: view) 

这是我通常用于我的平移手势的代码。它还倾斜块,而平移:

func pan(gesture:UIPanGestureRecognizer) { 

    let panLocationInView = gesture.locationInView(view) 
    let panLocationInD = gesture.locationInView(d) 

    switch gesture.state { 
    case .Began: 
     animator.removeAllBehaviors() 
     let offset = UIOffsetMake(panLocationInD.x - CGRectGetMidX(d.bounds), panLocationInD.y - CGRectGetMidY(d.bounds)) 
     attachmentBehaviour = UIAttachmentBehavior(item: d, offsetFromCenter: offset, attachedToAnchor: panLocationInView) 
     animator.addBehavior(attachmentBehaviour!) 
    case .Changed: 
     attachmentBehaviour?.anchorPoint = panLocationInView 
    case .Ended: 
     animator.removeAllBehaviors() 
     animator.addBehavior(UISnapBehavior(item: d, snapToPoint: view.center)) 
    default: 
     break 
    } 

} 

enter image description here