如何使用完成处理程序将图像放入 SwiftUI 视图中 [英] How to use a completion handler to put an image in a SwiftUI view
问题描述
我已经尝试过这个,但我不知道如何在 SwiftUI 视图中使用结果:
I have tried this, but I didn't know how to use the results in a SwiftUI View:
func getProfilePicture(_ completion: @escaping ((UIImage) -> Void)) {
Alamofire.request(GIDSignIn.sharedInstance()?.currentUser.profile.imageURL(withDimension: 75) ?? "https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
completion(image)
}
}
}
如果你能帮忙,我想把完成处理程序返回的图像放在这个视图中:
If you can help, I would like to put the returned image from the completion handler in this view:
struct ProfileView: View {
let profileInfo = ProfileInfo()
var placeHolderImage = Image(systemName: "person")
var body: some View {
Group {
placeHolderImage
.clipShape(Circle())
.overlay(
Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
.padding(10)
}
}
}
我希望它返回一个 UIImage 以便我最终可以在 SwiftUI 视图中使用它.我已经尝试使用带有 @escaping 完成处理程序的方法,但我不知道如何使用它来解决问题.谢谢!
I would like this to return a UIImage so I can eventually use it in a SwiftUI view. I have already tried using a method with an @escaping completion handler, but I couldn't figure out how to use it to fix the issue. Thanks!
推荐答案
你可以试试这个:
struct ProfileView: View {
@State var placeHolderImage = Image(systemName: "person")
var body: some View {
Group {
placeHolderImage
.clipShape(Circle())
.overlay(
Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
.padding(10)
}.onAppear{
getProfilePicture{ image in
self.placeHolderImage = Image(uiImage: image)
}
}
}
}
当ProfileView
出现时,它会调用getProfilePicture
.image in
(调用函数时)中指定的image
是完成处理程序通过的内容(completion(image)
).然后您可以做的是将您的 placeHolderImage
更改为您在 getProfilePicture
中获得的内容,但在此之前,您需要将 uiImage
变成一个图片
.还要确保您将 @State
关键字添加到您的变量中,以便一旦它更改您的 View
就会更新.
When ProfileView
appears it will call getProfilePicture
. The image
specified in image in
(when calling the function) is what the completion handler passes through (completion(image)
). What you can then do is change your placeHolderImage
to what you get in getProfilePicture
, but before you do that you need to make your uiImage
into an Image
. Also make sure you add the @State
keyword to your variable so once it changes your View
is updated.
希望有帮助!
这篇关于如何使用完成处理程序将图像放入 SwiftUI 视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!