金氧

Auto Layout 使用心得(三)—— 22 行代码实现拖动回弹

简介

本文中,我们将一起使用 UIPanGestureRecognizer 和 Auto Layout,通过 22 行代码实现拖动回弹效果。

搭建界面

删除首页中间的按钮,添加一个 View ,设置一种背景色便于辨认,然后对其进行绝对约束:

Image1

拖动一个 UIPanGestureRecognizer 到该 View 上:

Image2

界面搭建完成。

属性绑定

切换到双向视图,分别右键拖动 UIPanGestureRecognizer 和该 View 的 Top Space 的 Auto Layout 属性到 ViewController 中绑定,然后将 UIPanGestureRecognizer 右键拖动绑定:

Image3

编写代码

class ViewController: UIViewController {
    
    var middleViewTopSpaceLayoutConstant: CGFloat!
    var middleViewOriginY: CGFloat!
    
    @IBOutlet weak var middleView: UIView!
    @IBOutlet weak var middleViewTopSpaceLayout: NSLayoutConstraint!
    @IBOutlet var panGesture: UIPanGestureRecognizer!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        panGesture.addTarget(self, action: Selector("pan"))
        middleViewTopSpaceLayoutConstant = middleViewTopSpaceLayout.constant
        middleViewOriginY = middleView.frame.origin.y
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func pan() {
        if panGesture.state == UIGestureRecognizerState.Ended {
            UIView.animateWithDuration(0.4, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                self.middleView.frame.origin.y = self.middleViewOriginY
                }, completion: { (success) -> Void in
                    if success {
                        self.middleViewTopSpaceLayout.constant = self.middleViewTopSpaceLayoutConstant
                    }
            })
            return
        }
        let y = panGesture.translationInView(self.view).y
        middleViewTopSpaceLayout.constant = middleViewTopSpaceLayoutConstant + y
    }

}

查看效果

Image

22 行代码,拖动回弹效果完成!

« 奇妙的 Docker Inspect 模版 Auto Layout 使用心得(二)—— 实现三等分 »