iOS 17 `viewAligned` ScrollView 快速滑动会跳过视图

问题描述 投票:0回答:1

我正在摆弄 iOS 17 的新 ScrollView API,并且遇到了

viewAligned
scrollTargetBehavior
的小意外行为。

@State private var colors: [Color] = Array(repeating: [.red, .orange, .yellow, .blue], count: 100)

ScrollView(.horizontal) {
  LazyHStack(spacing: 8) {
    ForEach(colors, id: \.self) { colors in
      color
        .containerRelativeFrame(.horizontal) { length, _ in
          length - 32 
        }
    }
  }
  .scrollTargetLayout()
  .padding(.horizontal, spacing)
  .padding(.trailing, 16)
}
.scrollTargetBehavior(.viewAligned)

enter image description here

您会注意到,当我开始得更快时,一秒钟后视图开始快速滚动,滚动的视图比我滑动的次数多得多。我想知道是否有办法禁用此功能,以便滚动视图仅在我滑动时才滑动,并且不会自动跳过某些视图(如 gif 中所示)。

ios swift swiftui scrollview
1个回答
0
投票
.scrollTargetBehavior(.paging)

scrollTransition()
一起使用,如下所示:
import SwiftUI

private struct ContentView: View {
    @State private var colors: [Color] = [.red, .orange, .yellow, .blue]
    @State private var size: CGSize = .zero
    private static let pageWidth: CGFloat = 250
    
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack(spacing: 0) {
                ForEach(colors, id: \.self) { color in
                    color
                        .cornerRadius(40)
                        .frame(width: Self.pageWidth)
                        .padding(.horizontal, (size.width - Self.pageWidth) / 2)
                }
                .scrollTransition(axis: .horizontal) { content, phase in
                    content.offset(x: phase.value * -100)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.paging)
        .onChangeSize { self.size = $0 }
    }
}

#Preview {
    ContentView()
}

.onChangeSize()

只是获取滚动视图大小的帮助器,如下所示:

https://gist.github.com/mshibanami/ff9493be35c0e16f325c8d28ba4ffbe2
这就是它的工作原理:

demo FWIW,苹果今天发布了这个新的 WWDC 视频,其中解释了

scrollTransition()

的奇特用例,尽管他们的代码似乎出于说明目的进行了简化:

https://developer.apple.com/videos/play/wwdc2024/ 10151/?时间=89

© www.soinside.com 2019 - 2024. All rights reserved.