KGFloatingDrawer抽屉组件的使用

By | 2015年9月13日

前言

抽屉组件用的还是比较多的,在swift项目中,我们可以使用KGFloatingDrawer这个项目来做,它的github地址:https://github.com/KyleGoddard/KGFloatingDrawer

使用起来还是很方便的,还提供了demo。这里记录下如何使用。

第一步,创建需要显示的ViewController

所谓抽屉组件,其实就是预先设置好几个界面(ViewController),打开App时默认显示中间的ViewController,当接收到打开左侧ViewController的命令时,中间的退下,左边的补上(其实就是使用了位置移动、转场效果等)。

1)新建一个项目后,把默认的ViewController当作Center ViewController;

2)新建两个View Controller文件,分别命名为LeftViewController和RightViewController;

3)在storyboard文件中,拖入两个View Controller,把这2个View Controller分别关联LeftViewController和RightViewController。

4)分别设置三个ViewController的StoryBoard ID为:left、center、right

第二步,在AppDelegate中写代码

首先加入下面代码。

提供了一个KGDrawerViewController属性,最后需要把这个ViewController作为Root viewController。

private var _drawerViewController: KGDrawerViewController?
var drawerViewController: KGDrawerViewController {
    get {
        if let viewController = _drawerViewController {
            return viewController
        }
        return prepareDrawerViewController()
    }
}
func prepareDrawerViewController() -> KGDrawerViewController {

    let drawerViewController = KGDrawerViewController()
    drawerViewController.centerViewController = viewControllerForStoryboardId("center")
    drawerViewController.leftViewController = viewControllerForStoryboardId("left")
    drawerViewController.rightViewController = viewControllerForStoryboardId("right")
    //背景图片
    drawerViewController.backgroundImage = UIImage(named: "sky3")

    _drawerViewController = drawerViewController
    return drawerViewController
}
private func drawerStoryboard() -> UIStoryboard {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    return storyboard
}
private func viewControllerForStoryboardId(storyboardId: String) -> UIViewController {
    let viewController: UIViewController = drawerStoryboard().instantiateViewControllerWithIdentifier(storyboardId) as! UIViewController
    return viewController
}

在启动事件方法didFinishLaunchingWithOptions中,为window设置Root viewController:

window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = drawerViewController
window?.makeKeyAndVisible()

这样,默认界面就使用了KG提供的ViewController,它包含了我们创建的三个viewController,默认显示center。

第三步,触发事件中,打开左边抽屉(LeftViewController)或者右边抽屉(RightViewController)

在center viewController中,放置两个按钮,分别打开左边和右边的viewController。对应的action事件代码如下:

@IBAction func leftViewShow(sender: UIButton) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.drawerViewController.toggleDrawer(KGDrawerSide.Left, animated: true) { (finished) -> Void
in
    }
}
@IBAction func rightViewShow(sender: UIButton) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.drawerViewController.toggleDrawer(KGDrawerSide.Right, animated: true) { (finished) -> Void in
    }
}

效果