Использование .отредактировано и AsyncImage вместе

#swiftui #xcode13

Вопрос:

Я хотел бы использовать .отредактировано для всего представления, пока изображение не будет успешно загружено в AsyncImage.. В настоящее время я не могу найти способ завершить это.. Моя последняя попытка была такой..

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

Ответ №1:

Самое близкое решение-использовать onDisappear модификатор, который срабатывает, когда изображение исчезает (что означает, что изображение было загружено

 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)