SwiftUI ScrollView 根据下拉列表的更改以编程方式滚动到顶部

Lea*_*ode 1 ios swift swiftui

我有以下代码:

var body: some View {
    
    VStack {

        ScrollView {
            
            VStack {
            
                ForEach(1...7, id: \.self) { num in
                    
                    Text("\(num)")
                        .font(.title3)
                        .padding([.top, .bottom], 5)
                        .onTapGesture {
                
                            self.getGames()
                                
                        }
                
                }
                    
            }
                    
        }

        ScrollView() {
        
            GameCell(games: $games, picks: self.$playerPicks) 
            
        }
        .onAppear(perform: getGames) 

    }

}
Run Code Online (Sandbox Code Playgroud)

它根据num的值获取所有游戏和全部;因为它应该基于.onAppear(perform: getGames)

当选择 num 时,它会使用 GameCell 刷新主 ScrollVeiw,但是如果主 ScrollView (带有 GameCells)滚动到任何位置,当数据刷新时,它会停留在该位置...有没有办法让它滚动到主 ScrollView 的顶部(带有 GameCells)?

更新

我更新了上面的代码,有两个滚动视图,我想让第二个滚动视图在每次在第一个滚动视图中选择新值时将 GameCell 滚动到顶部。

Geo*_*e_E 5

您可以使用ScrollViewReader文档HWS 文章)。

对于您的用例,我们需要将 保存在变量ScrollViewProxy@State,以便可以在闭包外部访问它。像这样使用它:

struct ContentView: View {
    
    @State private var reader: ScrollViewProxy?
    
    var body: some View {
        VStack {
            ScrollView {
                VStack {
                    ForEach(1 ... 7, id: \.self) { num in
                        Text("\(num)")
                            .font(.title3)
                            .padding([.top, .bottom], 5)
                            .onTapGesture {
                                self.getGames()
                                
                                print("Tap:", num)
                                // Scroll to tag 'GameCell-top'
                                reader?.scrollTo("GameCell-top", anchor: .top)
                            }
                    }
                }
            }
            
            ScrollView {
                ScrollViewReader { reader in
                    LinearGradient(
                        gradient: Gradient(colors: [.red, .blue]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                    .frame(height: 1000)
                    .id("GameCell-top")  // <- ID so reader works
                    .tag("GameCell-top")  // <- Tag view for reader
                    .onAppear {
                        self.reader = reader  // <- Set current reader proxy
                    }
                    
                    // You can uncomment this view and do a similar thing to the VStack above
//                    GameCell(games: $games, picks: self.$playerPicks)
                }
            }
            .onAppear(perform: getGames)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果(我滚动底部滚动视图,然后点击顶部从 1 到 7 的任意数字):

结果