Reputation: 416
I use SwiftUI. I need a custom view. The custom view width should be equal to the superview width. The custom view contains two image views, aligning left and right respectively. Each image view has the same width and height (aspect ratio = 1). Two image views have 10 points space. I will display different size images in the image view (scale aspect fill).
If I use GeometryReader
, I can set the image view frame dynamically, but how to set the GeometryReader
frame dynamically? If I use HStack
without GeometryReader
, the image views frames are variable. How to do this in SwiftUI?
Upvotes: 5
Views: 14269
Reputation: 3061
Perhaps some variant of the following:
struct CustomView: View {
var body: some View {
HStack(spacing: 10) {
Image(systemName: "heart.fill")
.resizable()
.aspectRatio(1, contentMode: .fit)
Image(systemName: "heart.fill")
.resizable()
.aspectRatio(1, contentMode: .fit)
}.frame(maxWidth: .infinity)
}
}
Both images maintain a 1:1 aspect ratio, with 10 points of spacing between them, but are allowed to grow horizontally using the .frame
modifier.
Replace Image(systemName: "heart.fill")
with a desired image source as needed.
If your source image asset does not have a 1:1 aspect ratio, set the contentMode
to .fill
, and constrain the frame height of either the HStack
or the CustomView
inside its parent using .frame(height: ..)
.
Upvotes: 6