在这里我得到的图像从链接
struct CustomImageView: View {
var urlString: String
@ObservedObject var imageLoader = ImageLoaderService()
@State var image: UIImage = UIImage()
var body: some View {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width:100, height:100)
.onReceive(imageLoader.$image) { image in
self.image = image
}
.onAppear {
imageLoader.loadImage(for: urlString)
}
}
}
class ImageLoaderService: ObservableObject {
@Published var image: UIImage = UIImage()
func loadImage(for urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
DispatchQueue.main.async {
self.image = UIImage(data: data) ?? UIImage()
}
}
task.resume()
}
}
在这里,我通过链接显示收到的照片,并尝试通过.contextMenu
保存它
VStack {
CustomImageView(urlString: "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png")
.contextMenu {
Button(action: {
}) {
HStack {
Text("Save image")
Image(systemName: "square.and.arrow.down.fill")
}
}
}
}
当你点击一张照片时,一个.contextMenu
打开并有一个保存按钮,但照片没有保存,我该怎么办?
1条答案
按热度按时间rks48beu1#
在按钮操作中添加:
其中image是一个
UIImage
,所以你需要从你的模型中传递图像,并将其传递给上面的代码片段。完整代码: