首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIKit动态-将视图捕捉到父视图中心

UIKit动态-将视图捕捉到父视图中心
EN

Stack Overflow用户
提问于 2016-09-17 22:39:17
回答 1查看 212关注 0票数 0

我试着构建像tinder一样的界面,当手指被释放时,我想让view捕捉到父视图的中心。我试图用快照行为和平移手势识别器来实现它,但我看到了倒下视图的动画。

我的代码如下

代码语言:javascript
复制
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
    }
}
}
EN

回答 1

Stack Overflow用户

发布于 2016-09-18 01:06:23

您应该将UIDynamicAnimator的referenceView设置为查看而不是d。

代码语言:javascript
复制
animator = UIDynamicAnimator(referenceView: view)

下面是我平移手势通常使用的代码。它还会在平移时倾斜块:

代码语言:javascript
复制
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
    }

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39548027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档