SECRET OF CSS

ScrollView With Paging in SwiftUI | by Sasha Myshkina | Sep, 2022


This article will help you build the SwiftUI element looking like UIPageViewController in UIKit.

1*gACyUEafffr2ZZs3criw A
This is the element I implemented in my SwiftUI project

‘ScrollView with paging in SwiftUI’ was the exact query I typed into Google when trying to implement horizontal scroll with paging in my SwiftUI project. However, I surfed the Internet for a couple of hours only to find out that this quite a simple task in UIKit is not so obvious in SwiftUI.

Developers here and there are creating too complicated views to mimic UIPageViewController in SwiftUI. Some of them suggest using SwiftUI internal APIs the way it cannot be considered safe after all. Without further ado, let’s investigate the ways paging could be recreated in ScrollView.

If all the ScrollViews in your project will be paged (meaning you won’t ever need a classic scrolling view), the simplest way is to set UIScrollView.appearance().isPagingEnabled = true.

However, remember that UIScrollView.appearance() should be set once.

And constantly switching true or false on UIScrollView.appearance().isPagingEnabled is not the best choice after all.

The most convenient and right way to make ScrollView with paging is actually not using ScrollView at all, but using TabView!

Despite the fact that SwiftUI TabView is UIKit’s UITabViewController look-alike, it has some additional internals.

From iOS 14 you now can use TabView with .tabViewStyle modifier to create paging UI element. Let’s dive into some code. First, let’s create basic card model, that will contain data (title, subtitle, description, card background color and id) that our views use.

Static function getExampleModels(count: Int) exists only for illustration purposes, so I can quickly create some mock models that have different background colors.

Now switch to ContentView and add TabView(). This struct has two initilizers: TabView(selection: Binding<Hashable>?, content: () -> View) or TabView(content: () -> View).

We’ll go with the second option because in this tutorial we won’t need to know which card is now selected. With ForEach we’re adding all the mock models we have.

And finally adding .tabViewStyle modifier to create a beautiful paging effect (line 23). You may also have noticed that I use indexDisplayMode: .never.

It was used on purpose because I don’t want classic dots displaying page indices below the cards.

You may want to display the dots, then you should stick to .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always).

1*FwV ijjktRRMpjrgAUzvFw

Here you are. Now you can add custom fonts, images, buttons, etc. to recreate the exact page you need. This example on GitHub: git@github.com:sashamyshkina/tabViewExample.git



News Credit

%d bloggers like this: