问题描述
当创建一个 List
视图时,onAppear
会以您期望的方式触发该列表中的元素:只要您滚动到该元素,onAppear代码>触发器.但是,我正在尝试实现这样的水平列表
When creating a List
view onAppear
triggers for elements in that list the way you would expect: As soon as you scroll to that element the onAppear
triggers. However, I'm trying to implement a horizontal list like this
ScrollView(.horizontal) {
HStack(spacing: mySpacing) {
ForEach(items) { item in
MyView(item: item)
.onAppear { \\do something }
}
}
}
使用此方法,onAppear
会立即为所有项目触发,也就是说:立即,但我想要与 List
视图相同的行为.我该怎么做呢?是否有手动触发 onAppear 或控制视图加载的方法?
Using this method the onAppear
triggers for all items at once, that is to say: immediately, but I want the same behavior as for a List
view. How would I go about doing this? Is there a manual way to trigger onAppear, or control when views load?
为什么我要实现这一点:我制作了一个自定义 Image
视图,该视图仅在出现时才从 URL 加载图像(并同时替换占位符),这适用于List
视图,但我希望它也适用于我的水平列表".
Why I want to achieve this: I have made a custom Image
view that loads an image from an URL only when it appears (and substitutes a placeholder in the mean time), this works fine for a List
view, but I'd like it to also work for my horizontal 'list'.
推荐答案
根据 SwiftUI 2.0 (XCode 12 beta 1),这终于在本地解决了:在 LazyHStack
(或任何其他带有 Lazy 前缀的网格或堆栈)中,元素只会在它们出现在屏幕上时初始化(并因此触发 onAppear
).
As per SwiftUI 2.0 (XCode 12 beta 1) this is finally natively solved:In a LazyHStack
(or any other grid or stack with the Lazy prefix) elements will only initialise (and therefore trigger onAppear
) when they appear on screen.
这篇关于从 SwiftUI 的 ScrollView 列表中获取 onAppear 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!