SwiftUI 随着持续时间自动滚动

use*_*935 5 xcode ios swift swiftui

我正在尝试实现一个 ScrollView,它自动滚动可见到数组的末尾。AppStore 中有一些示例,其中内容开始自动滚动,您可以慢慢地看到它。使用下面的代码,它将自动滚动到最后一项,而不会看到它。如何为其添加持续时间或动画以便我可以看到它滚动?

ScrollView(.horizontal, showsIndicators: false) {
    ScrollViewReader {
        scrollView in
            LazyHStack {
                ForEach(self.drinkNames, id: \.self) {
                    drink in
                        ShowContent(drink: drink)
                        .padding(.leading)
                }
            }
            .onAppear {
                scrollView.scrollTo(drinkNames[drinkNames.endIndex - 1])
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 0

您只需要添加一个动画,如下所示:

.onAppear {
    withAnimation {
        scrollView.scrollTo(drinkNames[drinkNames.endIndex - 1])
    }
}
Run Code Online (Sandbox Code Playgroud)