Issue #821
Suppose we have a 16:9 preview Image and we want the title Text to be the same width
First we need PreferenceKey to store and sync size
struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value = .zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
For our Image, we use a GeometryReader
in the background with invisible View Color.clear
to get its size, then sync to our preference key.
@State private var previewImageSize: CGSize = .zero
Image(uiImage: image)
.resizable()
.aspectRatio(16/9, contentMode: .fit)
.frame(height: 180)
.background(
GeometryReader { geo in
Color.clear
.preference(
key: SizePreferenceKey.self,
value: geo.size
)
}
)
.onPreferenceChange(SizePreferenceKey.self) { preferences in
self.previewImageSize = preferences
}
Then in our Text, we set frame with maxWidth
based on the previewImageSize
State
VStack(alignment: .leading {
title
host
}
.padding(8)
.frame(maxWidth: previewImageSize.width, alignment: .leading)