SwiftUI: how to create a Tab View
It’s common in iOS apps to use a Tab View. The one with a few choices at the bottom, and you can completely switch what’s in the screen by tapping the icon / label.
SwiftUI conveniently provides us a view called TabView
, which makes it easy to implement such a UI pattern.
Here’s the simplest possible example of a TabView:
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
Text("First")
.tabItem {
Label("First", systemImage: "tray")
}
Text("Second")
.tabItem {
Label("Second", systemImage: "calendar")
}
}
}
}
And here’s the result:
See? We have a TabView
view, and inside it, we have 2 views.
Both are Text
views to make it simple.
Their tabItem
modifier will add them to the TabView
with a label provided as a Label
view.
Of course you will want to use a custom view instead of Text
in most cases.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025