This is a follow-up question from Content hugging priority behaviour in SwiftUI.
I have a List with async-loaded images for each row, which has its height set using a GeometryReader. Full code here:
struct CountryCell: View {
let country: Country
@State var childSize: CGSize = .init(width: 0, height: 50)
var body: some View {
HStack {
AsyncImage(url: Endpoints.flag(countryCode: country.flagCode).url, placeholder: Image("flag"))
.aspectRatio(contentMode: .fit)
.frame(width: DeviceMetrics.size.width * 0.25, height: self.childSize.height)
VStack(alignment: .leading, spacing: 5) {
Text("Country: ").bold() + Text(self.country.name)
Text("Capital: ").bold() + Text(self.country.capital)
Text("Currency: ").bold() + Text(self.country.currency)
}
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.background(
GeometryReader { proxy -> AnyView in
DispatchQueue.main.async {
self.childSize = proxy.size
}
return AnyView(Color.clear)
})
}
}
}
Run it, the images won't replace the placeholder (maybe 1 in 10 will randomly show up), although the network requests are made. I can't figure it out, but have a hunch it's a race condition during triggering layout by the GeometryReader and the AsyncImage. If you replace:
.frame(width: DeviceMetrics.size.width * 0.25, height: self.childSize.height)
with:
.frame(width: DeviceMetrics.size.width * 0.25)
then the images will show up correctly. Similarly, if you comment out the GeometryReader, things will start to work too.
Any hints would be much appreciated.