SwiftUI-List控件跳转到指定索引

197 阅读1分钟

前言

SwiftUI中,在ScrollView或List的控件中实现跳转到指定的索引元素。

满足点击或首次加载时,优先展示指定索引的元素。

实现代码

import SwiftUI

struct ContentView: View {
    @State private var scrollToElement: Int? = nil
    
    var body: some View {
        VStack {
            Button(action: {
                scrollToElement = 50
            }) {
                Text("Scroll to Element 50")
            }
            ScrollViewReader { scrollView in
                List {
                    ForEach(0..<100) { index in
                        Text("Element \(index)")
                            .id(index)
                    }
                }
                .onChange(of: scrollToElement) { element in
                    if let element = element {
                        withAnimation {
                            scrollView.scrollTo(element, anchor: .top)
                        }
                    }
                }
            }
        }
    }
}

实现效果

image.png