Sergio Bost
Sergio Bost

Reputation: 3209

Using .redacted & AsyncImage together

I would like to use .redacted on the entire view until the image is successfully loaded into AsyncImage.. Currently I cannot find a way to complete this.. My last attempt was this..

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?
        }
}

Upvotes: 0

Views: 1161

Answers (1)

cedricbahirwe
cedricbahirwe

Reputation: 1396

The closest solution is to use onDisappear modifier which is triggered when the view disappears (which mean the image had loaded

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)

Upvotes: 1

Related Questions