1

My view contains a scrollView with SwiftUI.Section with fixed header. The SwiftUI.Section is a list of items, each item have a list of entries with dynamic height.

I created a custom scroll view that return the offset while scrolling. I get the first visible index while scrolling only with fixed height item:

private func calculateSectionHeight(section: TimelineDisplayable.Section) -> CGFloat {
    let entryHeight: CGFloat = 200 // this should be dynamic
    let sectionHeight = entryHeight * CGFloat(section.items.count)
    return sectionHeight
}

private func calculateFirstVisibleSectionIndex(offset: CGFloat, geoProxy: GeometryProxy) -> Int {
    let offsetY = offset + geoProxy.size.height
    var accumulatedHeight: CGFloat = 0
    if let sections = self.viewModel.timelineDisplayable.value?.sections {
        for (index, section) in sections.enumerated() {
            let sectionHeight = calculateSectionHeight(section: section)
            accumulatedHeight += sectionHeight

            if accumulatedHeight >= offsetY {
                return index
            }
        }
        return sections.count - 1
    }
    return 0
}

I want to detect the first visible item while scrolling with dynamic heights of entries.

  • Does this answer your question? [Get first visible index from LazyHStack in SwiftUI](https://stackoverflow.com/questions/70630776/get-first-visible-index-from-lazyhstack-in-swiftui) – Yrb Jul 07 '23 at 14:18

0 Answers0