Search code examples
imageswiftuiscrollviewheightsdwebimage

Images ScrollView of Uniform Size


I am building the equivalent of a collection view with SwiftUI. I have been able to get the layout I want, however, I cannot make all images of the same height (let's say 100 pixels talk for example). How could I resize the images to to be 100 pixels tall with a contentAspectFill (I don't care if images get cut off a little), but still maintain the leading and trailing boundaries.

NewsList.swift

ScrollView {
    ForEach(newsArray, id:\.self) { article in
        Button(action: {
           //stuff here 
        }) {
           NewsCard(article: article)
        }
        .buttonStyle(PlainButtonStyle())
    }
    .padding(.horizontal)
}

NewsCard.swift

VStack(alignment: .leading) {
    WebImage(url: article.imageURL)
        .resizable()
        .indicator(.activity)
        .transition(.fade)
        .scaledToFill()
        .clipped()
        .cornerRadius(14.0, antialiased: true)
    Text(article.date.formatted)
        .font(.lightMedium)
    Text(article.title)
        .font(.regularLarge)
}
.padding(.top)

I am using SDWebImageUI for the Image fields, but that shouldn't matter. As you can see from my screenshot, not all of my images are uniform in height.

Screenshot


Solution

  • Not sure I understood what's bad here, but try the following

    VStack(alignment: .leading) {
        WebImage(url: article.imageURL)
            .resizable()
            .frame(maxWidth: .infinity, maxHeight: _your_desired_height_here)  // << 
    ...