前言:开始写文章这么久还没写过Swift的,今天来给大家讲解用Swift简单封装一个抽屉控件。
原理:利用UIViewController
的addChildViewController
方法来将要展示的抽屉的控制器添加到定制的控制器中管理,通过对主页面添加拖拽手势,及图层切换来实现左右拖拽显示侧边抽屉的效果。先来看一下效果图如下:
下面我们来看具体的定制代码,首先创建一个继承自
UIViewController
的控制器,实现代码如下:
import UIKit
// 抽屉的显示区域占屏幕宽度的百分比
fileprivate let DrawerWidthScale : CGFloat = 0.7
// 蒙版层最高透明度
fileprivate let CoverMaxAlpha : CGFloat = 0.5
// 屏幕宽
fileprivate let kScreenWidth : CGFloat = UIScreen.main.bounds.size.width
class RHDrawerController: UIViewController, UIGestureRecognizerDelegate {
var mainVC : UIViewController?
var leftVC : UIViewController?
var rightVC : UIViewController?
var drawerWidth : CGFloat!
var emptyWidth : CGFloat!
init(mainVC: UIViewController?, leftVC: UIViewController?, rightVC: UIViewController?) {
super.init(nibName: nil, bundle: nil)
self.mainVC = mainVC
self.addChildViewController(self.mainVC!)
self.view.addSubview((self.mainVC?.view)!)
self.leftVC = leftVC
self.addChildViewController(self.leftVC!)
self.view.insertSubview((self.leftVC?.view)!, at: 0)
self.rightVC = rightVC
self.addChildViewController(self.rightVC!)
self.view.insertSubview((self.rightVC?.view)!, at: 0)
self.drawerWidth = DrawerWidthScale * kScreenWidth
self.emptyWidth = kScreenWidth - self.drawerWidth
}
fileprivate var startPoint : CGPoint!
fileprivate var coverView : UIView!
override func viewDidLoad() {
super.viewDidLoad()
addSubviews()
}
func addSubviews() {
let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panView(pan:)))
pan.delegate = self;
self.view.addGestureRecognizer(pan)
if coverView == nil {
coverView = UIView.init(frame: self.view.bounds)
coverView.backgroundColor = UIColor.black
coverView.alpha = 0
coverView.isHidden = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapCoverView(tap:)))
coverView.addGestureRecognizer(tap)
self.mainVC?.view.addSubview(coverView)
}
}
// MARK: - pan event
func panView(pan: UIPanGestureRecognizer) {
switch pan.state {
case UIGestureRecognizerState.began:
self.startPoint = self.mainVC?.view.center
break
case UIGestureRecognizerState.changed:
panChange(pan: pan)
break
case UIGestureRecognizerState.ended:
if (self.mainVC?.view.frame.minX)! > self.drawerWidth / 2.0 {
showLeftViewController(animated: true)
} else if (self.mainVC?.view.frame.maxX)! < self.drawerWidth / 2.0 + self.emptyWidth {
showRightViewController(animated: true)
} else {
showMainViewController(animated: true)
}
break
default:
break
}
}
func panChange(pan: UIPanGestureRecognizer) {
// 拖拽的距离
let translation = pan.translation(in: self.view)
// 移动主控制器
self.mainVC?.view.center = CGPoint.init(x: self.startPoint.x + translation.x, y: self.startPoint.y)
// 判断是否设置了左右菜单
if self.rightVC == nil && (self.mainVC?.view.frame.minX)! <= CGFloat(0) {
self.mainVC?.view.frame = self.view.bounds
}
if self.leftVC == nil && (self.mainVC?.view.frame.minX)! >= CGFloat(0) {
self.mainVC?.view.frame = self.view.bounds
}
// 滑动到边缘位置后不可以继续滑动
if (self.mainVC?.view.frame.minX)! > self.drawerWidth {
self.mainVC?.view.center = CGPoint.init(x: (self.mainVC?.view.bounds.size.width)! / 2.0 + self.drawerWidth, y: (self.mainVC?.view.center.y)!)
}
if (self.mainVC?.view.frame.maxX)! < self.emptyWidth {
self.mainVC?.view.center = CGPoint.init(x: (self.mainVC?.view.bounds.size.width)! / 2.0 - self.drawerWidth, y: (self.mainVC?.view.center.y)!)
}
// 判断显示左菜单还是右菜单
if (self.mainVC?.view.frame.minX)! > 0.0 {
// 显示左菜单
self.view.sendSubview(toBack: (self.rightVC?.view)!)
// 更新左菜单位置
updateLeftVCFrame()
// 更新蒙版透明度
self.coverView.isHidden = false
self.coverView.alpha = CoverMaxAlpha * (self.mainVC?.view.frame.minX)! / self.drawerWidth
} else if (self.mainVC?.view.frame.minX)! < 0 {
// 显示右菜单
self.view.sendSubview(toBack: (self.leftVC?.view)!)
// 更新右菜单位置
updateRightVCFrame()
// 更新蒙版透明度
self.coverView.isHidden = false
self.coverView.alpha = CoverMaxAlpha * (kScreenWidth - (self.mainVC?.view.frame.maxX)!) / self.drawerWidth
}
}
// MARK: - tap event
func tapCoverView(tap: UITapGestureRecognizer) {
showMainViewController(animated: true)
}
// MARK: - pan delegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// 设置navigation子视图不可拖拽
if self.mainVC is UINavigationController {
let nav = self.mainVC as! UINavigationController
if nav.viewControllers.count > 1 && (nav.interactivePopGestureRecognizer?.isEnabled)! {
return false
}
}
// 如果mainVC是tabBarController 设置navigation子视图不可拖拽
if self.mainVC is UITabBarController {
let tabbar = self.mainVC as! UITabBarController
let nav = tabbar.selectedViewController as! UINavigationController
if nav.viewControllers.count > 1 && (nav.interactivePopGestureRecognizer?.isEnabled)! {
return false
}
}
// 设置拖拽响应范围
if gestureRecognizer is UIPanGestureRecognizer {
let actionWidth : CGFloat = self.emptyWidth
let panPoint = touch.location(in: gestureRecognizer.view)
if panPoint.x <= actionWidth || panPoint.x > self.view.bounds.size.width - actionWidth {
return true
} else {
return false
}
}
return true
}
// MARK: - 设置抽屉弹出收起动画
func showMainViewController(animated: Bool) {
UIView.animate(withDuration: animationDuration(animated: animated), animations: {
var frame : CGRect? = self.mainVC?.view.frame
frame?.origin.x = 0
self.mainVC?.view.frame = frame!
self.updateLeftVCFrame()
self.updateRightVCFrame()
self.coverView.alpha = 0
}) { (finished) in
self.coverView.isHidden = true
}
}
func showLeftViewController(animated: Bool) {
if self.leftVC == nil {
return
}
self.view.sendSubview(toBack: (self.rightVC?.view)!)
self.coverView.isHidden = false
UIView.animate(withDuration: animationDuration(animated: animated), animations: {
self.mainVC?.view.center = CGPoint.init(x: (self.mainVC?.view.bounds.size.width)! / 2.0 + self.drawerWidth, y: (self.mainVC?.view.center.y)!)
self.leftVC?.view.frame = self.view.bounds
self.coverView.alpha = CoverMaxAlpha
})
}
func showRightViewController(animated: Bool) {
if self.rightVC == nil {
return
}
self.view.sendSubview(toBack: (self.leftVC?.view)!)
self.coverView.isHidden = false
UIView.animate(withDuration: animationDuration(animated: animated), animations: {
self.mainVC?.view.center = CGPoint.init(x: (self.mainVC?.view.bounds.size.width)! / 2.0 - self.drawerWidth, y: (self.mainVC?.view.center.y)!)
self.rightVC?.view.frame = self.view.bounds
self.coverView.alpha = CoverMaxAlpha
})
}
// MARK: - update leftVC and rightVC frame
func updateLeftVCFrame() {
self.leftVC?.view.center = CGPoint.init(x: ((self.mainVC?.view.frame.minX)! + self.emptyWidth) / 2, y: (self.leftVC?.view.center.y)!)
}
func updateRightVCFrame() {
self.rightVC?.view.center = CGPoint.init(x: (self.view.bounds.width + (self.mainVC?.view.frame.maxX)! - self.emptyWidth) / 2, y: (self.rightVC?.view.center.y)!)
}
// MARK: - private
// 动画时长
func animationDuration(animated: Bool) -> TimeInterval {
return animated ? 0.25 : 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这个类已经把抽屉的功能实现了,这里对于左右抽屉是否存在没有做很细的划分,如果有需要可以做相应的修改,这里不再多说。
接下来说一下如何来使用,一般抽屉都用在主界面,即可以将抽屉直接设置成rootViewController
,同时可以在AppDelegate
里边添加一个抽屉的属性如下:
var window: UIWindow?
var drawerController : RHDrawerController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
// 主页面
let main = RHTabBarController()
// 左侧抽屉
let left = LeftViewController()
// 右侧抽屉
let right = RightViewController()
let rootVC = RHDrawerController.init(mainVC: main, leftVC: left, rightVC: right)
self.drawerController = rootVC
window?.rootViewController = rootVC
window?.makeKeyAndVisible()
return true
}
如此就可以很方便在主页面及左右抽屉页面来获取抽屉控制器来开关抽屉。
因为不同的需求实现的效果也是不同的,所以大家可以根据自己的需求来实现不同的效果。具体的调用在这就给大家简单示范一下:
import UIKit
class FirstViewController: RHViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "左抽屉", style: .done, target: self, action: #selector(clickLeftItem(item:)))
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "右抽屉", style: .done, target: self, action: #selector(clickRightItem(item:)))
let button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 50))
button.center = CGPoint.init(x: self.view.bounds.size.width / 2, y: self.view.bounds.size.height / 2)
button.backgroundColor = UIColor.random
button.addTarget(self, action: #selector(clickButton(sender:)), for: .touchUpInside)
self.view.addSubview(button)
}
// 点击左抽屉弹出左侧抽屉
func clickLeftItem(item: UINavigationItem) {
(UIApplication.shared.delegate as! AppDelegate).drawerController?.showLeftViewController(animated: true)
}
// 点击右抽屉弹出右侧抽屉
func clickRightItem(item: UINavigationItem) {
(UIApplication.shared.delegate as! AppDelegate).drawerController?.showRightViewController (animated: true)
}
func clickButton(sender: UIButton) {
let detail = SecondViewController()
self.navigationController?.pushViewController(detail, animated: true)
}
}
如果大家还有什么不清楚的,我写了demo在GitHub上,大家可以去下载来看看,地址如下:https://github.com/guorenhao/RHDrawer
最后还是希望该文章能够帮助到有需要的猿友们,愿我们能够共同学习进步,在开发的道路上越走越远!谢谢!
网友评论