ray*_*ayx 9 scrollview ios swiftui onappear
请参阅下面的示例代码:
struct TestView: View {
var body: some View {
ScrollViewReader { proxy in
List {
ForEach(1...30, id: \.self) { item in
Text("\(item)")
.id(item)
}
}
.onAppear {
proxy.scrollTo(8, anchor: .topLeading)
}
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink("test") {
TestView()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
两个观察结果:
如果我不放入TestViewin NavigationLink(例如,直接放入ContentView),代码可以正常工作。
以下差异可以解决该问题:
.onAppear {
- proxy.scrollTo(8, anchor: .topLeading)
+ DispatchQueue.main.async() {
+ proxy.scrollTo(8, anchor: .topLeading)
+ }
}
Run Code Online (Sandbox Code Playgroud)
有谁知道根本原因是什么?解决方法表明这是一个时间问题,这解释了我的观察结果 1,其中没有导航动画。那么,是否是因为当onAppear()运行时,动画仍在进行中,因此proxy.scrollTo()默默地失败了?但如果是这样,苹果不应该提供一个onAppear()在动画完成后运行的版本吗?当前的解决方法看起来太老套了。我在网上找到了它,有不同的版本,有的使用async(),有的使用asyncAfter(),这表明没有一个是可靠的。
| 归档时间: |
|
| 查看次数: |
1242 次 |
| 最近记录: |