A lot of apps these days have some kind of side menu which slide out when you select a little hamburger button on the navigation bar. In this blog I will be going over a simple method to create a side menu. Our slide out menu will look like this:
- Create a new project in Xcode.
- Open Main.storyboard from the project navigator on the left of Xcode. Drag and drop the navigation bar from the object library to the view controller (iPhone in the workspace)
- Next drag and drop a bar button form object library to the navigation bar. We will use this button to show the menu bar
- Click on assistant editor button on the top right corner of Xcode, to display the view controller in split screen with the storyboard
- Create a IBAction by pressing control key on your keyboard and dragging in to the view controllers coding area. Name it showMenuBar and don’t forget to select connection type as Action.
- Create a function named setupMenuBar just below the showMenuBar function, it will have all the coding necessary for setting our slide out menu bar
- At the top of view controller just below the class statement, create a variable menuBar of type UIView as following:
let menuBar = UIView()
- Copy the following code inside setupMenuBar()
//1 – Here we set the menuBar’s background color to yellow so that its visible on the screen
//2 – Adding menuBar to the view hierarchy
//3 – Set the menuBar’s frame such that its out of the device’s screen area
- Next add the following code inside the showMenuBar()
Here we change the frame of menuBar inside the animate closure so that it slides out of the left side of the device and covers 3/4 of the screen width on selecting the fast forward bar button.
- Create a function named hideMenu() just below the setupMenuBar() and add the following code inside it. This function will contain the code necessary to hide the menuBar
In this function we animate the menuBar view back out of the device’s visible screen area. In CGRect the y-coordinate, width and height parameters remain the same but the x coordinate changes to the negative of screen width. You can also choose any large enough random value which takes the view out of visible screen.
- Last call the setupMenuBar() from the viewDidLoad() method and add a tap gesture recognizer to the menuBar as following:
we call the hideMenu function when the menubar is tapped. You can have other elements call hideMenu function.
- Run the app and see the magic 🙂
- Download all the source code from here.