SwiftUI:以编程方式在 ScrollView 上动画滚动?

问题描述

我需要以编程方式为滚动视图的滚动设置动画。滚动视图包含一个 HStack 或一个 vstack。我测试的代码是这样的:

        ScrollViewReader { proxy in
            ScrollView(.horizontal,showsIndicators: false) {
                HStack(spacing: spacing) {
                    
                    ForEach(cids,id: \.self) { cid in

                        ....
                                
                    }
                    
                }
                .onAppear {
                    withAnimation(Animation.easeInOut(duration: 4).delay(3)) {
                        proxy.scrollTo(testCid)
                    }
                    
                }
            }
            .frame(maxWidth: w,maxHeight: w / 2)
        }

滚动视图确实落在带有 testCid 的项目上,但是它没有动画。 一旦视图出现在屏幕上,滚动视图就已经在 testCid...

如何为滚动设置动画?

解决方法

如果您从其他地方(例如 Button 操作)而不是从 onAppear 修饰符启动交互式滚动,则交互式滚动有效。我猜这是故意的行为,以防止用户在视图出现时看到滚动(或 SwiftUI 中的错误......)。一个丑陋的解决方法是使用 DispatchQueue.main.async:

推迟动画
import SwiftUI

struct ContentView: View {
    let words = ["planet","kidnap","harbor","legislation","soap","management","prejudice","an","trunk","divide","critic","area","affair"]

    @State var selectedWord: String?

    var body: some View {
        ScrollViewReader { proxy in
            VStack(alignment: .leading) {
                ScrollView(.horizontal,showsIndicators: false) {
                    HStack(spacing: 10) {
                        ForEach(words,id: \.self) { word in
                            Text(word)
                                .background(self.selectedWord == word ? Color.yellow : nil)
                                .id(word)
                        }
                    }
                }

                Button("Scroll to random word") {
                    withAnimation(Animation.easeInOut(duration: 1)) {
                        let word = words.randomElement()
                        self.selectedWord = word
                        proxy.scrollTo(word)
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.async {   // <--- workaround
                    withAnimation(Animation.easeInOut(duration: 1).delay(1)) {
                        let word = self.words.last
                        self.selectedWord = word
                        proxy.scrollTo(word)
                    }
                }
            }
        }
        .padding(10)
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...