BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.