问题描述
我需要以编程方式为滚动视图的滚动设置动画。滚动视图包含一个 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)
}
}