我尝试构建类似界面的tinder,并且我希望View在弹出手指时弹跳到父视图的中心。我尝试使用快照行为和平移手势识别器来实现它,但是我看到了下降视图的动画。
我的代码正在关注
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 :(得分: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
}
}