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

SwiftUI中scrollTo与scrollTargetBehavior冲突问题求助

SwiftUI中scrollTo配合iOS17滚动API的居中失效问题

我在SwiftUI里复刻Snapchat相机滤镜的滚动效果:借助iOS17新滚动API,手动滚动时每个圆形可以自动居中,效果正常;但点击调用scrollTo方法时,圆形无法保持居中。尝试多种锚点仍无法适配所有圆形,有时仅最后几个圆形能正常工作,首个圆形完全失效。

滚动效果演示

若移除scrollTargetBehavior(.viewAligned)和scrollTargetLayout,scrollTo功能恢复正常。以下是复现问题的简化代码:

import SwiftUI

@main
struct scrollApp: App {
    var body: some Scene {
        WindowGroup {
            GeometryReader(content: { outerProxy in
                ScrollViewReader(content: { proxy in
                    ScrollView(.horizontal, showsIndicators: false) {
                        LazyHStack(spacing: 0) {
                            ForEach(0...10, id: \.self) { index in
                                Circle()
                                    .frame(width: 100, height: 100)
                                    .foregroundStyle(.primary)
                                    .id(index)
                                    .onTapGesture {
                                        print("tap \(index)")
                                        withAnimation {
                                            proxy.scrollTo(index, anchor: .center)
                                        }
                                    }
                            }
                        }
                        .padding(.horizontal, outerProxy.size.width * 0.5 - 100/2)
                        .scrollTargetLayout()
                    }
                    .scrollTargetBehavior(.viewAligned)
                    .overlay {
                        Circle()
                            .stroke(.red, lineWidth: 10)
                            .frame(width: 100, height: 100)
                    }
                })
            })
            
        }
    }
}

仅接受纯SwiftUI解决方案,我已在UIKit中实现该功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:15:04