我的目标是有一个自定义AsyncImage视图,因为我需要验证我的请求。因此,我创建了一个自定义结构来实现这一点。现在我唯一的问题是,我想添加修改器到我加载的图像。
像这样:
CustomAsyncImageView(dataKey: dataKey) { image in
image
.resizable()
} placeholder: {
Rectangle()
}
What I tried:
struct CustomAsyncImageView<Content> : View where Content : View {
var content: Content
var image: Image?
// I left out the Image loading
public init<I, P>(dataKey: String, @ViewBuilder content: @escaping (Image) -> I, @ViewBuilder placeholder: @escaping () -> P) {
// I have this init from AsyncImage, but I have no idea how to initialize my properties
}
var body: some View {
if let image = image {
image
} else {
// show placeholder
}
}
}
是这种类型的初始化可能实现或我应该传递viewModifier作为参数?
你离得不远。您必须存储content
闭包以及placeholder
闭包,并在body
中执行它们。
我也不认为你需要@ViewBuilder
属性。
struct CustomAsyncImageView<I, P>: View where I: View, P: View {
let content: (Image) -> I
let placeholder: () -> P
var image: Image?
public init(dataKey: String, content: @escaping (Image) -> I, placeholder: @escaping () -> P) {
self.content = content
self.placeholder = placeholder
}
var body: some View {
if let image = image {
content(image)
} else {
placeholder()
}
}
}