Create your own Slider menu (Drawer) in Swift 3 – Xcode 8 – iOS 10

This article is updated with Swift 3 – Xcode 8 – iOS 10

Why to use a library everytime?

Slider Menu (Drawer)
Slider Menu (Drawer)

Let’s create our own Slide Menu (Drawer) in Swift 3.

1. Create New Project in Xcode 8 with Swift Language

2. Design the Menu in UIViewController

Menu UIViewController
Menu UIViewController

Declaration of Variables and Protocols (Delegate) :

Following method is for updating the Items in the Menu :

Following method is for click event and animation :


3. Now we will create a Base UIViewController to use anywhere in the project which control the delegate of menu.

First we will create this 3 lines Drawer Icon via Code

Preview_Slider_Drawer_ICon

Delegate (Protocol) method call :

To open a view controller by identifier :

Set the Restoration Identifier and Storyboard Identifier. If current view is open then we will not open it once again for that we have to check via Restoration Identifier.

4. Now We will assign this drawer to any of the UIViewController

We have to use only one method to add drawer (slide menu) self.addSlideMenuButton()


Source Code is available at the Github AKSwiftSlideMenu

GitHub AKSwiftSlideMenu Releases
GitHub AKSwiftSlideMenu Releases

You can download for both versions Swift 2 or Swift 3. From Releases Tab at GitHub AKSwiftSlideMenu .

I have uploaded a video for easy way to integrate AKSwiftSlideMenu in your project :

Check other blog posts about Swift

Happy Coding 🙂

  • canhpd

    Please indicate for me, how to show content of a view controller other in code below

    switch(index){
    case 0:
    print(“Home\n”, terminator: “”) //Move to that view
    //ex: i want show a table view in a file new view controller
    break
    case 1:
    print(“Play\n”, terminator: “”) //Move to that view
    break
    case 2:
    print(“Camera\n”, terminator: “”) //Move to that view
    break
    default:
    print(“default\n”, terminator: “”)
    }

    • Just Simple. You can code for push to new view controller witch contains the table view.

  • amr

    great work
    i used your code and added more features :
    1-small shadow on side
    2-menu button change to back button if opened
    3-increase animation duration
    4-open and close by swipe
    5-support arabic right menu too
    thanks

    • Great!
      Then upload it on your git so other can get help form it.

      Thanks a lot.

  • Klaas Kremer

    I lose the menu image when instantiating to another navigationcontroller.
    The menu works but the image is gone? Do you have a solution?
    Thanks!

    See below:

    code:
    switch(index){
    case 0:
    print(“Home\n”, terminator: “”)

    let navigationController:UINavigationController = UIStoryboard(name: “Main”, bundle: nil).instantiateViewControllerWithIdentifier(“klaasBase”) as! UINavigationController
    self.presentViewController(navigationController, animated: false, completion: nil)

    break

    • You have to add it again to the next view controller. The button will gone.

  • Klaas Kremer

    Well that is just my problem, the menu works fine in all other viewcontrollers I added. Only the image (3 horizontal stripes) is not visible. I can still tap it and the menu will slide in. But there is just no image. I must be missing something very basic…

    Maybe I should not use storyboard IDs, do you have an alternative way to push to another VC?
    Thanks for the fast reply!

  • Ahmed Elazab

    Hi Ashish,

    Many thanks for your effort to publish that post. I like sliding menu. I only have 1 questions regarding the issue that has been mentioned in the comments. Do you have any resolution for it – the menu button image that disappear when moving to another controller.

    Best regards,
    Ahmed

    • Yes. You have to add the button via addSlideMenuButton() method.

      • Francisckaner

        Hi !
        I’ ve add a push segue from the ViewController to the SecondViewController

        switch(index){
        case 0:
        print(“Home\n”, terminator: “”)
        break
        case 1:
        print(“Play\n”, terminator: “”)
        self.performSegueWithIdentifier(“secondSegue”, sender: nil)

        break
        case 2:
        print(“Camera\n”, terminator: “”)
        break
        default:
        print(“default\n”, terminator: “”)
        }

        On the SecondViewController I have extended BaseViewController and add self.addSlideMenuButton, after this I still can’ t get the Slider menu to work on the SecondViewController.

        Could you provide me some help, I’ m a starter on swift.
        Thanks a lot

        • I think segue will not be performed through that point. Because BaseViewController is actually virtual it is not available in storyboard.

          You have to find the controller and push to that controller.

          Thanks.

  • Alex

    Hi there,

    Great piece of code, nice and simple.

    Do you have a working sample with more controllers in the Storyboard? I am kind of new in Swift and i am having trouble understanding how to add a new controller and push to it when clicking on the menu.

    Any help would be appreciated.

    Cheers

    • When I get time, I will update the git with sample code with more controllers.

      Thanks

  • Radoslav Apostolov

    Great code! Simple and working! Thank you for it.
    Like some of the comments I too have a problem with the disappearing icon when trying to add it on a different view controller. The solution for me was to use a real image, instead creating one programmatically.
    Just change the line that sets the image to:
    btnShowMenu.setImage(UIImage(named:”examplePicture”), forState: UIControlState.Normal)
    and don’t forget to include a picture with that name in your assets.

    • Oh! Great.

      I have added that code when I was creating this tutorial but I want to give something new without image. May be the issue of creating that 3 lines next time.

      Your comment will help to others.

      Thanks.

      • Jay Mendez

        Hey Ashish,

        Thank you for a great simple to understand tutorial.

        I’m very new to coding so I hope I’m clear. Can anyone please tell me if there’s a way to load the connected view controllers to the same menu view. And if there is, can you please tell me the proper coding term for this process so I can look into it further.

        Thanks.

  • joe

    Thanks for the tutorial…
    I’ ve added a push segue from the ViewController to the SecondViewController(tabelViewController) segue function works as soon as i changed a switch(index) as below…

    switch(index){
    case 0:
    print(“Home\n”, terminator: “”)
    self.performSegueWithIdentifier(“1Segue”, sender: nil)
    break

    case 1:
    print(“Play\n”, terminator: “”)
    self.performSegueWithIdentifier(“2Segue”, sender: nil)
    break

    case 2:
    print(“Camera\n”, terminator: “”)
    self.performSegueWithIdentifier(“3Segue”, sender: nil)
    break

    default:
    print(“default\n”, terminator: “”)
    }

    and i created a new tableview inside the secondViewController and i done the code as below but Xcode throwing error as follow…i believe menuView not connecting to tableView somehow …. thanks in Advance.

    @IBOutlet var NewTableView: UITableView!

    let textCellIdentifier = “fCell”

    let swift = [“Fun”, “Family”, “Cute”, “Facebook”]

    override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return swift.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = swift[indexPath.row]

    return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let row = indexPath.row
    print(swift[row])
    }

    I am getting the following error code…help please..

    2016-01-25 11:23:39.944 AKSwiftSlideMenu[1191:318760] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UITableViewController loadView] instantiated view controller with identifier “UIViewController-Dcy-sl-lyS” from storyboard “Main”, but didn’t get a UITableView.’
    *** First throw call stack:
    (0x182f70f48 0x197a33f80 0x182f70e90 0x18860fb28 0x188503d44 0x18851c350 0x1886b5fb4 0x1885c2190 0x1885c1e6c 0x1885c1dd4 0x1884ff7ac 0x187cfeb58 0x187cf9764 0x187cf9624 0x187cf8cc0 0x187cf8a08 0x1884f59d8 0x182f27bd0 0x182f25974 0x182f25da4 0x182e54ca0 0x18e090088 0x18856cffc 0x100084208 0x1982828b8)
    libc++abi.dylib: terminating with uncaught exception of type NSException
    (lldb)

    • Segue will not work directly because the view controller does not contain that segue.

      So, do code for opening the view by using storyboard instance.

      Thanks.

  • Shrikant Tanwade

    Thanks

  • great tutorial, I try to make slide from right. I just found to move menu button to right, but I can’t find how change slide from right side.

    Thanks a lot

  • what method should I change for make slide from right?

  • Fabio Hening

    What should i do to change the side of this menu? In your example it is in the left side, i really need to use it in the right, can you give one more hand here?

    Thanks in advance.

    • You have to change the animation and view frame code as per your need.

      If I got time I will update tutorial with right menu.

      Thanks

  • Riddhi Shah

    hi..
    Nice tutorial.
    In this tutorial sideMenu starts below the navigationBar, But I want it above the navigationBar. How can I do that??

    • It will came only below the navigation bar. You have to search about how to get on the navigation bar.

      If I found something I will let you know.

      Thanks!

    • Rahul Gupta

      Hi Riddhi, did u got the solution..?

  • Really useful, thanks 🙂

  • Marco Almeida

    Thank you for the great tutorial!!! But tell me, is it possible to add this slide menu on a UITableViewController instead of a UIViewController? If yes, how could I do that please?

    • Ashish Kakkad

      Means main view as UITableViewController? or SideMenu as UIViewController?

      • Marco Almeida

        I mean the main view being a UITableViewController and we add the slide menu, is it possible?

        • Ashish Kakkad

          Yes! It is possible.

          • Marco

            Hi, can you please show how to do this ?

    • Ashish Kakkad

      If you are asking for SlideMenu UIViewController as UITableViewController. Then you will get full view (No Space at right side in your menu) Because we can customize UIViewController’s design and put table view or any view in it. We can not customize UITableViewController.

      • Marco Almeida

        So the only way to add the slide menu into a view that has a UITableView is by adding a normal UIViewController and add the UITableView and the slide menu, correct?

  • Marco Almeida

    Hey Ashish is there a way so that I can change the destination ViewController title when I segue to it from the Menu? I tried this code but is not passing the data to the destination:

    func slideMenuItemSelectedAtIndex(index: Int32) {
    let topViewController : UIViewController = self.navigationController!.topViewController!
    print(“View Controller is : (topViewController) n”, terminator: “”)
    switch(index){
    case 0:
    print(“Noten”, terminator: “”)
    var nextVC = AddSubcategoryVC()
    nextVC.categoryName = “Note”
    self.openViewControllerBasedOnIdentifier(“AddSubcategoryVC”)
    print(“On menu the cat is: (nextVC.categoryName)”)
    break
    default:
    print(“defaultn”, terminator: “”)
    }
    }

    On the destination viewcontroller I have this variable that is to get the data from the Menu:

    var categoryName = “”

    and it is returning ‘nil’. I also tried doing this:

    var categoryName : String!

    and this:

    var categoryName = String()

    all returning ‘nil’.

  • jaydev

    hi AShish ji can we add left/right slider in this code please suggest

    • Ashish Kakkad

      Yes, you can change the code for right slider. Or you can find new library at GitHub. Which contains left and right both slider.

  • AdityaSengarSwift

    hello i am getting eror in this line
    btnShowMenu.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    • Ashish Kakkad

      I think you are using old version of Swift. Use Xcode 7.3 or later with Swift 2.2. Or Post the whole error.

      • AdityaSengarSwift

        Hello sir need a solution about tableviewcell (I have one button in cell and textfield so if i click on button my textfield editable that i want so i cAN CHANGE VALUE

  • ray ray

    var button = UIButton(frame: CGRectMake(0,0,100,100))
    button.setTitle(“asdasd”, forState: .Normal)
    button.setTitleColor(UIColor.blackColor(), forState: .Normal) self.scrollView.addSubview(button) when i tried to add button on playvc, even the x and y coordinator is 0 ,but it seems not to place at correct position. please help

  • Pejo Zmaj

    This side menu opens trough whole screen, how can I make it to open to middle, open only to half of screen? Thanks

  • salem

    what if i have some classes as UITableViewControllers and others as UIViewController, how can i inherit the BaseViewController ?

    • Ashish Kakkad

      Yes. I know that issue we can not inherit ViewController in UITableViewController.

  • Amesh Padaval

    sir, I have created app but my func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is not calling , I don’t know what is issue

    • Ashish Kakkad

      Check dataSource and delegate of table. Check it’s correctly assigned to the current view or not.

  • Sayali Pitasys

    hello…can i hide the navigation bar while it displaying the drawer?

    • Ashish Kakkad

      When you open the menu then you have to hide the navigation bar.

      • Sayali Pitasys

        Thats what i am asking how do we hide the navigation bar?
        I have a view that is being blocked by this navigation bar.Please guide me on it.

  • zhakonai

    Hi! It is great. But can you do video tutorial?

  • Ivan Sinigaglia

    Thanks, it is great. Helped me a lot. Great work!

  • smzr anz

    hi bro,
    Great Work…
    in my project the status bar item colour is black but in yours its white.but i didn’t see any codes for that.how can i implement that??

  • Fabrice

    Hello, I am trying to learn and your tuto pleased me. I would add the slide menu to views that already exist. Can you tell me how to proceed, because I tried but I think I’m wrong. Thank you in advance

  • Brian Gibeault

    I implemented the slider into my App, and it compiles and runs, but when i press the button for the menu to slide, the app crashes and points to

    let menuVC : MenuViewController = self.storyboard!.instantiateViewController(withIdentifier: “MenuViewController”) as! MenuViewController

    As the point of failure. Any idea why this would happen?

    I have confirmed that the ViewControllers are named properly.

    • Brian Gibeault

      Nevermind.. my storyboard ID got deleted.. thanks

  • Costantino Lorusso

    Hi. I’m trying to use the slider in my app for iPad. Could you explain how to recall a UISplitViewController from the menu? I’m new in iOS and Swift programming.

    Tanks
    Costantino

  • Octavio Rojas

    I’m having this issue while trying to use the sidemenu I even wrote a stack overflow post to discuss it

    http://stackoverflow.com/questions/41495191/akswiftslidemenu-navigationcontrollers-uibarbuttonitem-badgevalues-conflict

  • Rahul Gupta

    Hi Ashish,
    I have one view controller in which i have added the naigation bar and added addSlideMenuButton() in viewDidLoad() but it is not creating the menu button.Please help..

  • Is there any function to put side menu on right side?

  • Jonatan Ramos

    Hi, the menu is great, I´m using it in a project but I have a problem. When I add the menu to a tableView and I scroll down, and then I tap the menu icon, it doesn’t appear. or only half of it, depends on how much i scroll down. It seems that the menu stays on top of the view even if the view is larger than the screen. Is there a way to make it show no matter where I am in the view?

  • Saleem Khan

    Hi Team,

    Thanks for sharing this article. I have implemented this menu in my app. I am using swift 3. Now i want to show user profile in the side menu also like user image and details etc.

    May I request you please share and similar document links with me.

    Thanks,
    Saleem

  • Padmini Beera

    Hi
    Thanks for the tuto. i am having problem in appending menu options. my app crashes in the func updateArrayMenuOptions()
    and says “unexpectedly found nil while unwrapping an Optional value”. what should i do that

    • Eric Kenzo

      Hello, same problem here.
      Did you solve it ?