Find tallest visible view in scrollview [SwiftUI]

Viewed 52

I am trying to find the tallest visible view in a ScrollView. For background, I am making a scrollable bar graph. Here's what I've got so far but onDisappear isn't being called.

    private var highestVisibleAmount: Double {
         visibleDates
            .compactMap { viewModel.transactions[$0] }
            .map {
                $0.map{ $0.amount }
                    .reduce(0, +)
            }
            .max() ?? 0
    }

    @State var visibleDates: Set<Date> = []
    
    var body: some View {
        ScrollView(Axis.Set.horizontal, showsIndicators: false) {
            ScrollViewReader { reader in
                LazyHStack(alignment: .bottom, spacing: 1) {
                    ForEach(viewModel.transactions.keys.sorted(), id: \.self) { date in
                        let transactions = viewModel.transactions[date] ?? []
                        BarView(viewModel: BarView.ViewModel(transactions: transactions, highestVisibleAmount: highestVisibleAmount))
                            .frame(width: viewModel.segmentLength)
                            .onAppear(perform: { visibleDates.insert(date)})
                            .onDisappear(perform: { visibleDates.remove(date)})
                    }
                }
            }
        }
        .frame(height: viewModel.chartHeight)
    }
0 Answers
Related