I'm trying to implement a view that has a subview that just renders an array of images. The number of images to draw varies.
This is my main view:
var body: some View {
List {
if !routeTrips.isEmpty {
ForEach(routeTrips, id: \.self) { trip in
Group {
Button(action: {
self.handleRouteTripTap(routeTrip: trip)
}) {
VStack {
HStack {
Image("bus")
.resizable()
.renderingMode(.template)
.foregroundColor(Color.black)
.frame(width:30, height: 30)
.padding(.leading, 10)
HStack {
Text("\(trip.LineToShow)")
.fontWeight(.bold)
.foregroundColor(Color.black)
Text("\(trip.Name)")
.foregroundColor(Color.black)
Spacer()
Text("\(trip.ArrivalTimeToShow)")
.foregroundColor(Color.black)
}
}
HStack{
if nil != trip.SubTrips {
ChangesRow(subTrips: trip.SubTrips ?? [])
.padding(.leading, 10)
}
Spacer()
if 0 < trip.Price {
Text("\(trip.Price)€")
.font(.subheadline)
.foregroundColor(.black)
}
}
}
}
.listRowBackground(Color(red: 239/255, green: 239/255, blue: 239/255, opacity: 1))
.padding(.top, 10)
}
}
} else {
Text("Sem viagens")
.foregroundColor(.black)
.listRowBackground(Color(red: 239/255, green: 239/255, blue: 239/255, opacity: 1))
}
}
}
The ChangesRow
is the view that draws one row with images and is implemented as follows:
var body: some View {
HStack {
ForEach(subTrips.indices, id: \.self) { i in
if subTrips[i].IsWalking {
Image("walking")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
} else {
HStack(spacing: 0) {
Image("A" == subTrips[i].Provider ? "subway" : "B" == subTrips[i].Provider ? "train" : "bus")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
Image("logo_\(subTrips[i].Provider)")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 15, height: 15)
}
}
if(self.subTrips.count - 1 != i) {
Image(systemName: "chevron.right")
.resizable()
.renderingMode(.template)
.aspectRatio(contentMode: .fit)
.foregroundColor(.gray)
.frame(width: 10, height: 10)
}
}
}
}
The problem I'm having is that If there are many images to draw, the view expands beyond the screen and gets all wonky. Any idea on how I can guarantee that despite the number of images, it will always be drawn visibly?
Where I render the Price
, I've tried writing a long text, and the view adjusts accordingly. Why doesn't it do the same with the images?
Thanks!
For anyone wondering how this was solved, it wasn't. I could not set the frame width because the number of images to draw could vary, and I wanted the images frame to be either 20/20 or 15/15.
I was able to achieve an acceptable result by implementing a ScrollView
that only scrolls horizontally.