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

SwiftUI:ScrollView结合.viewAligned与.scrollPosition()横竖屏切换时位置不更新

SwiftUI ScrollView横竖屏切换时滚动位置不更新问题

在配置了.scrollTargetBehavior(.viewAligned)和.scrollPosition()的SwiftUI ScrollView中,当设备横竖屏切换(视图尺寸发生变化)时,滚动位置无法自动更新,演示效果如下:

SwiftUIScrollView横竖屏滚动位置异常

测试代码

import SwiftUI

struct ContentView: View {
    let colors: [Color] = [.red, .yellow, .cyan, .blue, .teal, .brown, .orange, .indigo]
    @State private var selected: Int? = 0
    
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 0) {
                ForEach(0..<colors.count, id: \.self) { index in
                    Rectangle()
                        .fill(colors[index])
                        .containerRelativeFrame(.horizontal)
                        .overlay {
                            Text(colors[index].description)
                        }
                }
            }
            .scrollTargetLayout()
        }
        .scrollPosition(id: $selected)
        .scrollTargetBehavior(.viewAligned)
    }
}

#Preview {
    ContentView()
}

@main
struct ViewAlignedScrollBugApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

测试环境

  • Xcode 15.3 (15E204a)
  • iOS 17.3.1 iPhone真机
  • iOS 17.4模拟器

已向Apple提交反馈FB13685677,同时在开发者论坛发布相关帖子,想咨询:是否存在遗漏的配置?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 05:52:41