You need to enable JavaScript to run this app. SwiftUI中iOS13版本如何实现ScrollView水平滚动到指定索引?
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中iOS13版本如何实现ScrollView水平滚动到指定索引?

iOS 13 兼容ScrollView程序化滚动(支持水平滚动+按索引跳转)

你现有的实现思路是可行的,通过遍历视图层级获取底层UIScrollView的方式完全兼容iOS13,仅需对现有代码做少量修改即可满足水平滚动、按指定索引滚动的需求:

第一步:修改核心逻辑代码

调整ListScrollingProxy的枚举和滚动逻辑,新增水平滚动、按索引滚动的支持:

// 原有ListScrollingHelper无需修改
struct ListScrollingHelper: UIViewRepresentable {
    let proxy: ListScrollingProxy 

    func makeUIView(context: Context) -> UIView {
        return UIView() 
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        proxy.catchScrollView(for: uiView) 
    }
}

class ListScrollingProxy {
    enum Action {
        case verticalTop
        case verticalEnd
        case horizontalLeading
        case horizontalEnd
        case point(point: CGPoint)
        // 新增按索引滚动,需传入索引、item尺寸、滚动方向、item间距
        case index(_ idx: Int, itemSize: CGSize, spacing: CGFloat = 0, isHorizontal: Bool)
    }

    private var scrollView: UIScrollView?

    func catchScrollView(for view: UIView) {
        if nil == scrollView {
            scrollView = view.enclosingScrollView()
        }
    }

    func scrollTo(_ action: Action) {
        guard let scroller = scrollView else { return }
        var rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1))
        switch action {
        case .verticalTop:
            rect.origin.y = -scroller.contentInset.top
        case .verticalEnd:
            rect.origin.y = scroller.contentSize.height + scroller.contentInset.bottom - 1
        case .horizontalLeading:
            rect.origin.x = -scroller.contentInset.left
        case .horizontalEnd:
            rect.origin.x = scroller.contentSize.width + scroller.contentInset.right - 1
        case .point(let point):
            rect.origin = point
        case .index(let idx, let itemSize, let spacing, let isHorizontal):
            if isHorizontal {
                rect.origin.x = CGFloat(idx) * (itemSize.width + spacing) - scroller.contentInset.left
            } else {
                rect.origin.y = CGFloat(idx) * (itemSize.height + spacing) - scroller.contentInset.top
            }
        }
        scroller.scrollRectToVisible(rect, animated: true)
    }
}

// 原有分类无需修改
extension UIView {
    func enclosingScrollView() -> UIScrollView? {
        var next: UIView? = self
        repeat {
            next = next?.superview
            if let scrollview = next as? UIScrollView {
                return scrollview
            }
        } while next != nil
        return nil
    }
}

第二步:水平ScrollView使用示例

水平滚动场景按以下方式使用即可支持跳转到指定索引:

struct HorizontalScrollViewDemo: View {
    private let scrollingProxy = ListScrollingProxy()
    // 水平滚动的item固定尺寸+间距,可根据实际业务调整
    private let itemSize = CGSize(width: 100, height: 150)
    private let itemSpacing: CGFloat = 16

    var body: some View {
        VStack {
            // 跳转控制按钮
            HStack {
                Button("到最左侧") {
                    scrollingProxy.scrollTo(.horizontalLeading)
                }
                Button("跳转到第10个") {
                    scrollingProxy.scrollTo(.index(9, itemSize: itemSize, spacing: itemSpacing, isHorizontal: true))
                }
                Button("到最右侧") {
                    scrollingProxy.scrollTo(.horizontalEnd)
                }
            }
            .padding()

            // 水平ScrollView
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: itemSpacing) {
                    ForEach(0..<50) { i in
                        RoundedRectangle(cornerRadius: 8)
                            .fill(.blue.opacity(0.7))
                            .frame(width: itemSize.width, height: itemSize.height)
                            .overlay(Text("\(i)").foregroundColor(.white))
                            .background(
                                ListScrollingHelper(proxy: scrollingProxy)
                            )
                    }
                }
                .padding(.horizontal, 16)
            }
        }
    }
}

注意事项

  • 该实现依赖SwiftUI底层ScrollView对应UIScrollView的视图层级结构,目前iOS13到iOS17的层级结构均无变化,可正常使用,但不排除后续苹果调整层级结构导致失效的可能
  • 如果item尺寸是动态的,可以提前计算好对应索引的偏移量,调用.point(point: CGPoint(x: 偏移量, y: 0))的方式滚动即可
  • 垂直滚动场景按原有逻辑使用即可,新增的index case同样支持垂直滚动的索引跳转

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:27:03