首页 > 解决方案 > 在滚动视图中查找最高的可见视图 [SwiftUI]

问题描述

我试图在ScrollView. 对于背景,我正在制作一个可滚动的条形图。这是我到目前为止得到的,但onDisappear没有被调用。

    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)
    }

标签: iosarraysswiftswiftui

解决方案


推荐阅读