I am trying to align an image with a textbox in a Swift application.
How do I get this to look correct?
This is the version of code I have that is funky. I’ve tried a lot of things and I need help, please.
ForEach(listing.items, id: .self) { i in
VStack(alignment: .leading, spacing: 6) {
Image(i.itemImageUrl)
.resizable()
.scaledToFit()
.overlay(
ZStack {
Text("$ (i.priceOfItem)")
.font(.body)
.padding(5)
.foregroundColor(.white)
}
.background(Color.black)
.opacity(0.7)
.cornerRadius(12)
.padding(10),
alignment: .bottomTrailing)
Text("Description: (i.itemDescription)")
.frame(width: .infinity, alignment: .topLeading).padding(8)
.background(Color.gray.opacity(0.2))
.font(.body)
}
.padding()
I am aiming for the alignment on the left, but when the code renders within another view there’s a weird white space.
2
Answers
Did you checked if maybe the image itself has a white space?
If you want the images to fill the full width then you could use
ViewThatFits
to choose between scaled-to-fill and scaled-to-fit:You might also want to wrap the
ForEach
with aScrollView
.Your example code is using a deprecated version of the
.overlay
modifier. The modifiers.foregroundColor
and.cornerRadius
are also deprecated, use.foregroundStyle
and.clipShape
instead. And… you don’t need to nest theText
inside aZStack
. So I would suggest changing the overlay to the following:That just leaves the labels below the images. You might have noticed, your existing code was giving errors in the console:
This is because,
.infinity
is not valid as awidth
. However, it is valid asmaxWidth
, this is the only change needed here:Here is the fully-updated example: