SwiftUI – Horizontal Pages Carousel
Table of Contents
Horizontal page carousels are a common element in iOS interfaces for presenting pages in a horizontal, swipeable format.
They are particularly useful for showcasing views with varying content.
Code#
In SwiftUI, creating such elements is straightforward.
Let’s define a SwiftUIView
and use the following code:
import SwiftUI
struct PageSliderView: View {
// the data we want to present in each page,
// this can be as simple as an array of string or as complex as an array of compound views.
let pages = ["One", "Two", "Three"]
var body: some View {
TabView {
ForEach(pages, id: \.self) {
Text("Page \($0)")
.font(.title)
}
}
.tabViewStyle(PageTabViewStyle()) // set the tab view behaviour to page
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) // set the dot indicator to be visible
}
}
#Preview {
PageSliderView()
}
The code above showcases one of the advantages of declarative UI frameworks, where you describe what you want instead of instructing the computer how to do it.
This approach results in expressive and concise code.
Result#
The outcome is impressive, especially when you consider the minimal code required.
Conclusion#
SwiftUI is a powerful tool that enables us to focus on describing the UI. With just a few lines of code, we can achieve results that would necessitate significantly more code in UIKit.