Search code examples
iosswiftsdwebimage

How can I combine these two functions?


I am using SDWebImageSwiftUI to display images but need to supply an image of type binding for my ImageView structs within a ForEach loop.

How do I do this using SDWebImage?

Thank you!

struct ContentView: View {
   @ObservedObject var duplicateVM : DuplicateUserVM

   var body: some View {
      List { 
          ForEach(duplicateVM.users, id: \.id) { user in
             ImageView(idImage: WebImage(url: URL(string: user.idUrl)))
             //                           ^ How do I supply the URL??
        }
     }   
   }
} 

struct ImageView: View {
    @Binding var idImage: UIImage?  
    
    var body: some View {
       Image(uiImage: idImage).resizable()       
    }
}
    



                                           

Solution

  • Pass only the name and add all the code inside the ImageView.

    struct ContentView98: View {
       @ObservedObject var duplicateVM : DuplicateUserVM
    
       var body: some View {
          List {
            ForEach(duplicateVM.users, id: \.id) { user in
                 ImageView(idImage: user)
            }
         }
       }
    }
    
    struct ImageView: View {
        @Binding var idImage: String
        
        var body: some View {
            WebImage(url: URL(string: idImage)).resizable()
        }
    }
    

    Or create string init for the WebImage

    extension WebImage {
        init(string: String) {
            self.init(url: URL(string: string))
        }
    }
    
    struct ImageView: View {
        @Binding var idImage: String
        var body: some View {
            WebImage(string: idImage).resizable()
        }
    }