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
相关产品推荐
相关产品推荐

