公司项目一直没有推进, 只能自己写一些Swift代码, 准备全面转向Swift开发.
之前的项目中使用过抽屉效果, 一直都是使用第三方, 准备自己一个抽屉
最终效果
运行效果1. Storyboard
- 本人懒, 就没有搭UI, 使用两张截图
-
在 HomeViewController 中添加 UIPanGestureRecognizer, 并进行关联
屏幕快照 2016-05-18 16.12.41.png
2. MeunViewController
- 通过 Storyboard 的 取出 HomeViewController 的 view 添加到subview
- 给 HomeViewController 的 UIPanGestureRecognizer 添加响应事件
// 通过 Storyboard 取出 HomeViewController 的 view, 放在背景上
homeViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
self.view.addSubview(homeViewController.view)
// 绑定 UIPanGestureRecognizer
homeViewController.panGusture.addTarget(self, action: #selector(pan))
3.响应事件
struct Common {
static let screenWidth = UIScreen.mainScreen().bounds.size.width
static let screenHeight = UIScreen.mainScreen().bounds.size.height
}
var homeViewController: HomeViewController!
var distance: CGFloat = 0
let Proportion: CGFloat = 0.3
// 响应 UIPanGestureRecognizer 事件
@objc private func pan(recongnizer: UIPanGestureRecognizer) {
// 获取实时距离
let x = recongnizer.translationInView(self.view).x
let trueDistance = distance + x
// 如果 UIPanGestureRecognizer 结束, 则自动停靠
if recongnizer.state == UIGestureRecognizerState.Ended {
print(x)
// 判断停靠位置
if trueDistance > Common.screenWidth * Proportion {
showLeft()
} else {
showHome()
}
return
}
// 只添加左抽屉
if trueDistance < 0 {
return
}
recongnizer.view!.center = CGPointMake(self.view.center.x + trueDistance, self.view.center.y)
}
4 . 手势响应事件中方法
private func showLeft() {
distance = self.view.center.x * 1.5
doAnmation()
}
private func showHome() {
distance = 0
doAnmation()
}
private func doAnmation() {
UIView.animateWithDuration(0.3,
delay: 0,
options: .CurveEaseInOut,
animations: { () -> Void in
self.homeViewController.view.center = CGPointMake(self.view.center.x + self.distance, self.view.center.y)
},
completion: nil)
}
}
结语
只是实现了一个侧滑的效果, 并没有实现相关的功能, 待完善