Creating a bottom sheet using Swift — UIKit

This tutorial has been developed using Xcode 13.4.1 and Swift 5.6.1

1 — Context

From the past three months, I've worked on Vibefy, an app that calculates your mood based on your Apple Music history and suggests restaurants from Recife and Metropolitan Region based on the calculated mood. During the design phase, we made the decision to use a bottom Sheet in the Home page. However building it from scratch was quite challenging, as we could not find resources to implement this functionality the way we wanted. With that in mind, I decided to write this article as a guide for you to create your own Bottom Sheet programmatically.

2 — Setting up your project in Xcode

  • Open your Xcode and create a new Project

Once you've created a new project in Xcode, the default boilerplate comes with the Main.storyboard. Because you want to create a bottom Sheet programmatically (a non-Storyboard approach), you need to follow a few steps.

  • Delete the Main.storyboard file
  • Remove the key “Storyboard Name” in info.plist

Make sure you remove the key (click in the minus button), not only the value of it.

  • Remove the Main.storyboard reference from deployment info

If the project has a Storyboard file set as the Main interface, the window property will automatically be initialized and the RootViewController will be set as the storyboard’s initial View Controller. Due to the fact that you already removed the Main.storyboard, you need to initialize the window and set the RootViewController manually. For that, you need to modify the function scene in SceneDelegate file:

  • Create the main window

Default function:

After carrying out changes:

  • Now you've finished the setup section.

3 — Creating and setting up the bottom sheet UIView

  • Creating the Bottom Sheet UIView
  • Adding the Bottom Sheet View in View Controller
  • Result:

4 — Adding the gesture recognizer

The next step is to add a gesture recognizer to our Bottom Sheet view, thus you will use the UIPanGestureRecognizer from UIKit.

The “handlePanGesture” is an Objective-C method that handles the gesture recognized by the receiver.

  • Result:

5 — Limiting the movement

Notice that Bottom Sheet view movement doesn’t have limitation. This property can be added to the view by the modification of the “handlePanGesture” function.

  • Now, the view can only move in a specific range.
  • Result:

6 — Adding animation when the touch ends

You are almost done. You just need to implement the animation when touch ends. Modify the “handlePanGesture” function again.

  • Result:
It's Working!!

--

--