一起使用 .redacted 和 AsyncImage
Using .redacted & AsyncImage together
我想在整个视图上使用 .redacted,直到图像成功加载到 AsyncImage 中。目前我找不到完成此操作的方法。我最后一次尝试是这样的。
struct MyView: View {
var body: some View {
VStack {
//Other Views
AsyncImage(url: URL(string: "https://cdn2.thecatapi.com/images/7CGV6WVXq.jpg")!) { phase in
if let image = phase.image {
image
//Some image modifiers
self.imageLoaded = true // Of course this won't work in this closure but I cannot think of where else to put it.
}
}
}.redacted(reason: imageLoaded ? .placeholder : []) // <-- How to redact programmatically?
}
}
最接近的解决方案是使用 onDisappear
修饰符,它在视图消失时触发(这意味着图像已加载
VStack {
//Other Views
AsyncImage(url: URL(string: "https://cdn2.thecatapi.com/images/7CGV6WVXq.jpg")!) { phase in
if let image = phase.image {
image
} else {
// When the image is loading, or has failed to load
// You can use any view (example: a loading view or placeholder)
RoundedRectangle(cornerRadius: 10)
.onDisappear {
imageLoaded = true
}
}
}
.frame(width: 300, height: 300)
}
.redacted(reason: imageLoaded ? [] : .placeholder)
我想在整个视图上使用 .redacted,直到图像成功加载到 AsyncImage 中。目前我找不到完成此操作的方法。我最后一次尝试是这样的。
struct MyView: View {
var body: some View {
VStack {
//Other Views
AsyncImage(url: URL(string: "https://cdn2.thecatapi.com/images/7CGV6WVXq.jpg")!) { phase in
if let image = phase.image {
image
//Some image modifiers
self.imageLoaded = true // Of course this won't work in this closure but I cannot think of where else to put it.
}
}
}.redacted(reason: imageLoaded ? .placeholder : []) // <-- How to redact programmatically?
}
}
最接近的解决方案是使用 onDisappear
修饰符,它在视图消失时触发(这意味着图像已加载
VStack {
//Other Views
AsyncImage(url: URL(string: "https://cdn2.thecatapi.com/images/7CGV6WVXq.jpg")!) { phase in
if let image = phase.image {
image
} else {
// When the image is loading, or has failed to load
// You can use any view (example: a loading view or placeholder)
RoundedRectangle(cornerRadius: 10)
.onDisappear {
imageLoaded = true
}
}
}
.frame(width: 300, height: 300)
}
.redacted(reason: imageLoaded ? [] : .placeholder)