AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78948585
Accepted
markb
markb
Asked: 2024-09-04 20:13:17 +0800 CST2024-09-04 20:13:17 +0800 CST 2024-09-04 20:13:17 +0800 CST

当 `visibleItems` 为偶数时,SwiftUI 水平 ScrollView 初始加载时出现捕捉问题

  • 772

我正在ScrollViewSwiftUI 中构建一个水平对齐功能,将项目对齐到屏幕的中心。滚动时对齐功能运行良好,但视图首次加载时,初始项目会略微偏移,不会像预期的那样对齐到中心。

我发现问题出现在 的数量visibleItems为偶数时。当 的数量为奇数时visibleItems,初始对齐和捕捉从一开始就可以正常工作。

这是我的代码CircleScrollView:

struct CircleScrollView: View {

    @State(initialValue: 2)
    var initialPosition: Int

    @State(initialValue: 8)
    private var visibleItems: Int

    @State(initialValue: 0)
    private var currentIndex: Int

    private let spacing: CGFloat = 16

    var body: some View {
        ZStack(alignment: .leading) {

            // For visuals of screen centre
            Rectangle()
                .fill(Color.gray.opacity(0.2))
                .ignoresSafeArea()
                .frame(maxWidth: UIScreen.main.bounds.width / 2, maxHeight: .infinity, alignment: .leading)


            GeometryReader { geometry in

                let totalSpacing = spacing * CGFloat(visibleItems - 1)
                let circleSize = (geometry.size.width - totalSpacing) / CGFloat(visibleItems)

                ScrollViewReader { scrollViewProxy in
                    ScrollView(.horizontal) {
                        HStack(spacing: spacing) {
                            ForEach(1..<100) { index in
                                ZStack {
                                    Text("\(index)")
                                    Circle().fill(Color(.tertiarySystemFill))
                                }
                                .frame(width: circleSize, height: circleSize)
                                .id(index)
                            }
                        }
                        .scrollTargetLayout()
                        .padding(.horizontal, (geometry.size.width - circleSize) / 2)
                        .onAppear {
                            scrollViewProxy.scrollTo(initialPosition, anchor: .center)
                            currentIndex = initialPosition
                        }
                    }
                    .scrollIndicators(.never)
                    .scrollTargetBehavior(.viewAligned)
                }
            }
        }
    }
}

问题:

  • visibleItems当为偶数时,初始滚动位置会发生偏移。
  • visibleItems滚动或为奇数时可正常工作。

采取的步骤:

  • 检查了和间距的计算circleSize。
  • 通过调整填充来验证初始对齐。

问题:

  • 当初始项目为偶数时,如何确保其正确对齐visibleItems?
  • 有没有更好的方法来处理初始加载期间的对齐或捕捉?

示例模拟器加载不正确,但滚动时工作正常

  • 1 1 个回答
  • 48 Views

1 个回答

  • Voted
  1. Best Answer
    Benzy Neez
    2024-09-04T22:43:29+08:002024-09-04T22:43:29+08:00

    这个问题似乎与 上的水平填充有关HStack。它没有填充也能正常工作(但显然,只适用于不需要填充的位置)。

    我猜这ViewAlignedScrollTargetBehavior有点问题。作为一种解决方法,您可以尝试实现自己的ScrollTargetBehavior。

    我尝试了一下,发现该函数的updateTarget调用方式不同,取决于它是第一次显示还是响应滚动手势:

    • 首次显示时,目标的锚点为.center,目标宽度为圆的宽度。目标原点的 x 偏移量包含屏幕宽度的一半。

    • 有趣的是,首次演出时无需修正。所以这似乎是哪里ViewAlignedScrollTargetBehavior出了问题。

    • 当随后调用滚动手势时,目标锚点为零,目标宽度是容器的宽度(ScrollView)。

    • 零锚点似乎被解释为.topLeading。因此,在这种情况下,目标的 x 偏移与 的前缘有关ScrollView,而不是中心。

    • 我尝试更新目标锚点.center并调整目标宽度,但无法通过这种方法使其工作(它总是滚动太多)。最好保持目标锚点和宽度不变,并接受它与前缘相关。

    以下是特定于您的布局的自定义行为:

    struct StickyCentrePosition: ScrollTargetBehavior {
        let itemWidth: CGFloat
        let spacing: CGFloat
        let sidePadding: CGFloat
    
        func updateTarget(_ target: inout ScrollTarget, context: TargetContext) {
    
            // dx is the distance from the target anchor to the
            // leading edge of a centered item
            let dx = (target.anchor?.x ?? 0) == 0
                ? (context.containerSize.width / 2) - (itemWidth / 2)
                : 0
            let currentTargetIndex = (target.rect.origin.x + dx - sidePadding) / (itemWidth + spacing)
            let roundedTargetIndex = currentTargetIndex.rounded()
            let scrollCorrection = (roundedTargetIndex - currentTargetIndex) * (itemWidth + spacing)
            target.rect.origin.x += scrollCorrection
        }
    }
    

    由于您使用状态变量来记录所选位置,因此将其用作 的currentIndex效果很好。这样,它会在滚动时更新,并且不需要。只需将变量更改为可选项即可使其工作。.scrollPositionScrollViewScrollViewReader

    以下是完全更新的示例,现在适用于偶数和奇数个可见项目:

    struct CircleScrollView: View {
        let initialPosition = 2
        let visibleItems = 8
        let spacing: CGFloat = 16
        @State private var currentIndex: Int?
    
        var body: some View {
            ZStack {
    
                HStack(spacing: 0) {
                    Color.gray.opacity(0.2)
                    Color.clear
                }
                .ignoresSafeArea()
    
                GeometryReader { geometry in
                    let screenWidth = geometry.size.width
                    let totalSpacing = spacing * CGFloat(visibleItems - 1)
                    let circleSize = (screenWidth - totalSpacing) / CGFloat(visibleItems)
                    let sidePadding = (screenWidth - circleSize) / 2
    
                    ScrollView(.horizontal) {
                        HStack(spacing: spacing) {
                            ForEach(1..<100) { index in
                                ZStack {
                                    Text("\(index)")
                                    Circle().fill(Color(.tertiarySystemFill))
                                }
                                .frame(width: circleSize, height: circleSize)
                                .id(index)
                            }
                        }
                        .scrollTargetLayout()
                        .padding(.horizontal, sidePadding)
                    }
                    .scrollIndicators(.never)
                    .scrollTargetBehavior(
                        StickyCentrePosition(
                            itemWidth: circleSize,
                            spacing: spacing,
                            sidePadding: sidePadding
                        )
                    )
                    .scrollPosition(id: $currentIndex, anchor: .center)
                    .onAppear { currentIndex = initialPosition }
                }
            }
        }
    }
    
    • 1

相关问题

  • 将复制活动的序列号添加到 Blob

  • Packer 动态源重复工件

  • 选择每组连续 1 的行

  • 图形 API 调用列表 subscribedSkus 状态权限不足,但已授予权限

  • 根据列值创建单独的 DF 的函数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve