
安靜的辦公環(huán)境.jpg
前言:開始寫文章這么久還沒寫過Swift的,今天來給大家講解用Swift簡單封裝一個抽屜控件。
原理:利用UIViewController的addChildViewController方法來將要展示的抽屜的控制器添加到定制的控制器中管理,通過對主頁面添加拖拽手勢,及圖層切換來實現(xiàn)左右拖拽顯示側(cè)邊抽屜的效果。先來看一下效果圖如下:

RHDrawerController.gif
下面我們來看具體的定制代碼,首先創(chuàng)建一個繼承自
UIViewController的控制器,實現(xiàn)代碼如下:
import UIKit
// 抽屜的顯示區(qū)域占屏幕寬度的百分比
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)
// 判斷是否設(shè)置了左右菜單
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
}
// 滑動到邊緣位置后不可以繼續(xù)滑動
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 {
// 設(shè)置navigation子視圖不可拖拽
if self.mainVC is UINavigationController {
let nav = self.mainVC as! UINavigationController
if nav.viewControllers.count > 1 && (nav.interactivePopGestureRecognizer?.isEnabled)! {
return false
}
}
// 如果mainVC是tabBarController 設(shè)置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
}
}
// 設(shè)置拖拽響應(yīng)范圍
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: - 設(shè)置抽屜彈出收起動畫
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")
}
}
這個類已經(jīng)把抽屜的功能實現(xiàn)了,這里對于左右抽屜是否存在沒有做很細的劃分,如果有需要可以做相應(yīng)的修改,這里不再多說。
接下來說一下如何來使用,一般抽屜都用在主界面,即可以將抽屜直接設(shè)置成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()
// 左側(cè)抽屜
let left = LeftViewController()
// 右側(cè)抽屜
let right = RightViewController()
let rootVC = RHDrawerController.init(mainVC: main, leftVC: left, rightVC: right)
self.drawerController = rootVC
window?.rootViewController = rootVC
window?.makeKeyAndVisible()
return true
}
如此就可以很方便在主頁面及左右抽屜頁面來獲取抽屜控制器來開關(guān)抽屜。
因為不同的需求實現(xiàn)的效果也是不同的,所以大家可以根據(jù)自己的需求來實現(xiàn)不同的效果。具體的調(diào)用在這就給大家簡單示范一下:
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)
}
// 點擊左抽屜彈出左側(cè)抽屜
func clickLeftItem(item: UINavigationItem) {
(UIApplication.shared.delegate as! AppDelegate).drawerController?.showLeftViewController(animated: true)
}
// 點擊右抽屜彈出右側(cè)抽屜
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
最后還是希望該文章能夠幫助到有需要的猿友們,愿我們能夠共同學(xué)習(xí)進步,在開發(fā)的道路上越走越遠!謝謝!