且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当 ObservedObject 更改时,SwiftUI 视图不会更新

更新时间:2023-02-06 14:51:31

分享一些可能有帮助的经验.

Share some experiences that might help.

当我使用 ScrollView + ForEach + fetch 时,除非我通过其他方式触发视图刷新,否则不会显示任何内容.当我提供固定数据而不获取时,它会正常显示.我通过为 ScrollView 指定 .infinity 宽度解决了这个问题.

When I used ScrollView + ForEach + fetch, nothing shows until I trigger view refresh via other means. It shows normally when I supply fixed data without fetching. I solved it by specifying .infinity width for ScrollView.

我的理论是 ForEach 在 fetch 完成时重新渲染,但 ScrollView 不知何故不会调整其宽度以适应内容.

My theory is that ForEach re-renders when fetch completes, but ScrollView somehow does not adjust its width to fit the content.

您的情况类似.通过提供固定宽度的 Text,ForEach 可以在 init 期间计算其宽度,而 ScrollView 可以使用它来调整其宽度.但是在 fetch 的情况下,ForEach 的初始内容宽度为 0,ScrollView 也是如此.当获取完成时,ScrollView 不会相应地更新其宽度.

It is similar in your case. By supplying fixed width Text, ForEach can calculate its width during init, and ScrollView can use that to adjust its width. But in case of fetch, ForEach has initial 0 content width, and so is ScrollView. When fetch completes ScrollView does not update its width accordingly.

给 ScrollView 一些初始宽度应该可以解决你的问题.

Giving ScrollView some initial width should solve your problem.