Auto Layout 使用心得(四)—— 22 行代码实现拖动回弹
此系列文章代码仓库在 https://github.com/johnlui/AutoLayout ,有不明白的地方可以参考我的 Auto Layout 设置哦,下载到本地打开就可以了。
简介
本文中,我们将一起使用 UIPanGestureRecognizer 和 Auto Layout,通过 22 行代码实现拖动回弹效果。
搭建界面
删除首页中间的按钮,添加一个 View ,设置一种背景色便于辨认,然后对其进行绝对约束:

拖动一个 UIPanGestureRecognizer 到该 View 上:

界面搭建完成。
属性绑定
切换到双向视图,分别右键拖动 UIPanGestureRecognizer 和该 View 的 Top Space 的 Auto Layout 属性到 ViewController 中绑定:

然后将 UIPanGestureRecognizer 右键拖动绑定:

编写代码
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
}
}
查看效果

22 行代码,拖动回弹效果完成!
评论:
幻听
2016-01-26 13:52
2016-01-26 13:52
我把你的代码转为OC后发现UIView的这个执行动画的方法,持续时间以及延迟时间感觉无效啊,我的这个view拖动后放手立马回到原来的位置,并没有动画的过程,为啥
Ekulelu
2015-08-03 16:33
2015-08-03 16:33
博主的这个程序从竖直屏幕启动后切换到横屏,回滚的时候会出现跳跃。加上屏幕旋转处理之后可以消除。
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.middleViewTopSpaceLayoutConstant = self.middleViewTopSpaceLayout.constant
middleViewOriginY = middleView.frame.origin.y
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.middleViewTopSpaceLayoutConstant = self.middleViewTopSpaceLayout.constant
middleViewOriginY = middleView.frame.origin.y
}
CrazyPeter
2015-07-17 16:50
2015-07-17 16:50
非常感谢博主的教程,获益很多。
在此吐个槽,其实这个并没有过多的使用AutoLayout,只是需要约束的数值就可完成这个动画吧。
顺便问一下,博主是苹果内部的工程师嘛?
在此吐个槽,其实这个并没有过多的使用AutoLayout,只是需要约束的数值就可完成这个动画吧。
顺便问一下,博主是苹果内部的工程师嘛?





2016-08-19 14:52
1. 用约束之后,拖动手势为什么就只能用约束常量改变来实现了呢?
2. 视图动画结束后,设置约束变回初始值,但是会出现跳一下的情况(OC实现)