You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI ScrollView重置内容时出现异常行为的问题求助

SwiftUI ScrollView重置内容时出现异常行为的问题求助

各位好!我目前在SwiftUI中开发一个支持筛选功能的滚动列表(用ScrollView实现,本质就是个可筛选的列表),但在重置内容或者刷新的时候遇到了异常行为,想请大家帮忙看看问题出在哪。

我的ViewModel和视图结构大致如下:

class ViewModel: ObservableObject {
    @Published
    var isRefreshing = false
    var components: [Int] = Array(0...100)
    
    func refresh() {
        isRefreshing = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.isRefreshing = false
        }
    }
}
struct ContentView: View {
    @StateObject
    private var viewModel: ViewModel

    init() {
        _viewModel = StateObject(wrappedValue: ViewModel())
    }
    
    var body: some View {
        ScrollView(showsIndicators: false) {
            LazyVStack(spacing: .zero, pinnedViews: [.sectionHeaders]) {
                Section {
                    if viewModel.isRefreshing {
                        loadingView
                    } else {
                        ForEach(viewModel.components, id: \.hashValue) { _ in
                            Rectangle()
                                // 这里原本有更多样式代码,暂时简化展示
                                .frame(height: 60)
                                .padding(.horizontal)
                        }
                    }
                } header: {
                    // 头部视图,这里省略了具体样式
                    Text("列表标题")
                        .padding()
                        .background(Color.white)
                }
            }
        }
        .refreshable {
            viewModel.refresh()
        }
    }
    
    private var loadingView: some View {
        ProgressView()
            .padding()
    }
}

具体问题是:当我触发刷新操作,或者通过筛选功能重置components数组内容时,ScrollView会出现奇怪的行为——比如滚动位置突然跳转到顶部/某个奇怪的位置,或者列表元素的渲染出现错乱,有时候刷新状态结束后,新的列表内容不能正确显示出来。

我已经检查过@Published的使用,也尝试调整过LazyVStack的参数,但还是没能解决问题。有没有朋友遇到过类似的情况?或者能帮我排查下代码里的潜在问题吗?

备注:内容来源于stack exchange,提问作者André

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 08:44:35