UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Change displayed informations while scrolling

Forums > SwiftUI

Hi,

I have an Horizontal Scroll View which displays 3 cards, below it I have a list of related infos.

When scrolling the cards, how can I detect which card is currently displayed on screen in order to show the related and correct infos?

Thanks

2      

I added a tap gesture on the card so, when I click one, it automatically updates the list with the relevant infos. But I can't figure it out how to detect which card is currently on screen.

Maybe I have to calculate it using geometry reader or similar?

Any suggestion?

Thanks

2      

Hi! Maybe as an easier option for you to use TabView like so.

struct ContentView: View {
    @State private var pageIndex = 0

    private let data = [
        "Information for card Zero",
        "Information for card One",
        "Information for card Two",
        "Information for card Three",
        "Information for card Four",
        "Information for card Five",
        "Information for card Six"
    ]

    var body: some View {
        VStack(spacing: 20) {
            TabView(selection: $pageIndex) {
                ForEach(data.indices, id: \.self) { index in
                    Image(systemName: "\(index).circle")
                        .font(.largeTitle)
                        .frame(width: 300, height: 200)
                        .background(Color.red.gradient)
                        .cornerRadius(10)
                }
            }
            .frame(width: .infinity, height: 200)

            Text(data[pageIndex])
        }
        .tabViewStyle(.page)
        .indexViewStyle(.page(backgroundDisplayMode: .always)) // or you can hide with .never
    }
}

Well if it fits your purpose and design of course...

2      

If you still need to use ScrollView here is a good example. A bit verbose piece of code though... Credits to Daniel Saidi, cannot post link. Seems like too many spammers so HWS rejects insertion of some links now...

struct UsingCustomScrollView: View {
    @State private var pageIndex = 0
    @State private var offset: CGFloat = 0

    private let data = [
        "Information for card Zero",
        "Information for card One",
        "Information for card Two",
        "Information for card Three",
        "Information for card Four",
        "Information for card Five",
        "Information for card Six"
    ]

    var body: some View {
        let width: CGFloat = 300
        let height: CGFloat = 200
        VStack(spacing: 20) {
            ScrollViewWithOffset(.horizontal, showsIndicators: true) { offset in
                let offsetX = Int(round((offset.x / width)))
                pageIndex =  abs(offsetX)
                self.offset = offset.x
            } content: {
                LazyHStack {
                    ForEach(data.indices, id: \.self) { index in
                        Image(systemName: "\(index).circle")
                            .font(.largeTitle)
                            .frame(width: width, height: height)
                            .background(Color.red.gradient)
                            .cornerRadius(10)
                    }
                }
            }
            .frame(width: .infinity, height: height)

            Text("\(pageIndex)")
            Text("\(offset)")

            if pageIndex < data.count {
                Text(data[pageIndex])
            }
        }
        .padding(.horizontal)
    }
}

enum ScrollOffsetNamespace {
    static let namespace = "scrollView"
}

struct ScrollOffsetPreferenceKey: PreferenceKey {
    static var defaultValue: CGPoint = .zero
    static func reduce(value: inout CGPoint, nextValue: () -> CGPoint) {}
}

struct ScrollViewOffsetTracker: View {
    var body: some View {
        GeometryReader { geo in
            Color.clear
                .preference(
                    key: ScrollOffsetPreferenceKey.self,
                    value: geo.frame(in: .named(ScrollOffsetNamespace.namespace)).origin
                )
        }
        .frame(height: 0)
    }
}

private extension ScrollView {
    func withOffsetTracking(action: @escaping (_ offset: CGPoint) -> Void) -> some View {
        self.coordinateSpace(name: ScrollOffsetNamespace.namespace)
            .onPreferenceChange(ScrollOffsetPreferenceKey.self, perform: action)
    }
}

public struct ScrollViewWithOffset<Content: View>: View {

    public init(
        _ axes: Axis.Set = .vertical,
        showsIndicators: Bool = true,
        onScroll: ScrollAction? = nil,
        @ViewBuilder content: @escaping () -> Content
    ) {
        self.axes = axes
        self.showsIndicators = showsIndicators
        self.onScroll = onScroll ?? { _ in }
        self.content = content
    }

    private let axes: Axis.Set
    private let showsIndicators: Bool
    private let onScroll: ScrollAction
    private let content: () -> Content

    public typealias ScrollAction = (_ offset: CGPoint) -> Void

    public var body: some View {
        ScrollView(axes, showsIndicators: showsIndicators) {
            ZStack(alignment: .top) {
                ScrollViewOffsetTracker()
                content()
            }
        }
        .withOffsetTracking(action: onScroll)
    }
}

2      

Thank you so much!

I think the TabView solution is more natural using SwiftUI, it makes the code more easier and readable.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.