Creating a Custom Drawer in SwiftUI

iOS Guru
2 min readApr 24, 2023

SwiftUI is a powerful tool for creating user interfaces for iOS applications. With SwiftUI, developers can quickly build complex user interfaces without writing a lot of code. One of the most popular components of SwiftUI is the Drawer, which allows users to quickly and easily access a variety of content. In this article, we will explore how to create a custom Drawer in SwiftUI.

Creating the Drawer

The first step in creating a custom Drawer in SwiftUI is to create the Drawer itself. To do this, we will use a NavigationView and a List. The NavigationView will be used to display the content of the Drawer, while the List will be used to create the list of items that will be displayed in the Drawer.

The code for the Drawer is as follows:

struct DrawerView: View {
var body: some View {
NavigationView {
List {
// Content of the Drawer will go here
}
}
}
}

Next, we will add the content of the Drawer. To do this, we will add a ForEach loop to the List. The ForEach loop will loop through an array of items and create a NavigationLink for each item in the array. The NavigationLink will allow the user to navigate to the content associated with the item.

The code for the content of the Drawer is as follows:

struct DrawerView: View {
let items = ["Home", "Settings", "About"]
var body: some View {
NavigationView {
List {
ForEach(items, id: \.self) { item in
NavigationLink(destination: Text(item)) {
Text(item)
}
}
}
}
}
}

Adding the Drawer to the App

Now that we have created the Drawer, we need to add it to the app. To do this, we will use a NavigationView. The NavigationView will contain the content of the app, as well as the Drawer. The code for the NavigationView is as follows:

struct ContentView: View {
var body: some View {
NavigationView {
// Content of the app will go here

DrawerView()
}
}
}

Now, when the app is run, the Drawer will be displayed on the left side of the screen. The user can use the Drawer to navigate to the content associated with each item.

Conclusion

In this article, we have explored how to create a custom Drawer in SwiftUI. We have seen how to create the Drawer, add content to it, and add it to an app. With SwiftUI, creating custom Drawers is easy and can be done quickly.

--

--