JLively
JLively

Reputation: 152

Custom ScrollView Indicator in SwiftUI

Is it possible to create a custom horizontal indicator that has empty and filled circles to show how many images there are and the current position?

The below attempt uses a lazyHStack and OnAppear but, judging from the console output, it doesn't work properly since scrolling back and forth doesn't recall the onAppear consistently.

import SwiftUI

struct ContentView: View {
    let horizontalScrollItems = ["wind", "hare.fill", "tortoise.fill", "rosette" ]
    
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal, showsIndicators: false) {
                LazyHStack {
                    ForEach(horizontalScrollItems, id: \.self) { symbol in
                        Image(systemName: symbol)
                            .font(.system(size: 200))
                            .frame(width: geometry.size.width)
                            .onAppear(){print("\(symbol)")}
                            
                    }
                }
            }
        }
    }
}

This is the desired indicator. I'm just not sure how to properly fill and empty each circle as the user scrolls back and forth. Appreciate the help!

CustomCircleIndicator

Upvotes: 0

Views: 2862

Answers (1)

Apoorv
Apoorv

Reputation: 412

You can get the desired result using TabView() and PageTabViewStyle()

Note : This will work from SwiftUI 2.0

Here is the code :

struct ContentView: View {
    let horizontalScrollItems = ["wind", "hare.fill", "tortoise.fill", "rosette" ]
    
    var body: some View {
        GeometryReader { geometry in
            TabView(){
                ForEach(horizontalScrollItems, id: \.self) { symbol in
                    Image(systemName: symbol)
                        .font(.system(size: 200))
                        .frame(width: geometry.size.width)
                }
            }
            .tabViewStyle(PageTabViewStyle())
            .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
        }
    }
}

Result : enter image description here

Upvotes: 2

Related Questions