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

iOS 18下ScrollViewReader无法滚动到列表项的问题求助

iOS 18 中 ScrollViewReader.scrollTo 失效的解决办法

针对你遇到的 iOS 18 下scrollTo无法自动滚动到指定条目的问题,以下是几个实测有效的解决思路:

  • 延迟执行滚动操作
    iOS 18 中 List 的渲染时机可能比 iOS 17 晚,onAppear触发时列表条目还未完全渲染完成,导致scrollTo找不到目标。可以给滚动操作加一个极短的延迟:

    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            proxy.scrollTo(currentSection, anchor: .center)
        }
    }
    

    延迟时间可以根据列表长度微调,0.1 秒一般足够覆盖大部分场景。

  • 结合数据变化监听
    如果sections是异步加载的数据,仅靠onAppear可能无法确保数据已完全就绪。可以同时监听sections的变化,在数据加载完成后再执行滚动:

    .onAppear {
        scrollToTarget(proxy: proxy)
    }
    .onChange(of: sections) { _, _ in
        scrollToTarget(proxy: proxy)
    }
    
    // 抽成单独方法复用
    private func scrollToTarget(proxy: ScrollViewProxy) {
        guard !sections.isEmpty else { return }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
            proxy.scrollTo(currentSection, anchor: .center)
        }
    }
    
  • 确认目标 ID 的匹配性
    再次检查currentSection和section.key的类型和值是否完全一致。比如如果currentSection是可选类型,要确保它不为 nil;如果是自定义类型,要确认Equatable实现正确,或者直接用原始类型(如 String、Int)作为 ID。

  • 临时替换为 ScrollView 测试
    如果以上方法都无效,可以尝试将 List 替换为 ScrollView+LazyVStack,看看scrollTo是否正常工作,以此排查是不是 List 在 iOS 18 中的特定问题:

    ScrollViewReader { proxy in
        ScrollView {
            LazyVStack {
                ForEach(sections, id: \.key) { section in
                    SomeListItem(section: section)
                        .id(section.key)
                }
            }
        }.onAppear {
            proxy.scrollTo(currentSection, anchor: .center)
        }
    }
    

内容的提问来源于stack exchange,提问作者InsightClip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:03:13