I have a SwiftUI app. The main view lists the latest articles from a blog. I want the first article to be presented with larger text and a larger image, with the rest of the articles listed below.
The code that I have works, but there's a problem as the featured article row overflows the width of the container. This means that the image and text are off the edge of the screen to the left, and the navigation chevron is off the screen to the right. The "regular" article rows display as expected.
Here is the code for the main view and then then FeatureArticleRow.
struct LatestListView: View {
@StateObject private var vm = LatestViewModel()
@State private var showDetail = false
@State private var selectedArticle: String?
var body: some View {
NavigationView {
Group {
if vm.isLoading {
ProgressView("Data is loading…")
} else if let error = vm.error {
Text(error)
} else {
List {
if let firstArticle = vm.articles.first {
NavigationLink(destination: ArticleDetailView(slug: firstArticle.slug)) {
FeatureArticleRow(article: firstArticle)
}
}
ForEach(vm.articles.dropFirst(), id: \.slug) { article in
NavigationLink {
ArticleDetailView(slug: article.slug)
} label: {
ArticleRow(article: article)
}
}
}
.listStyle(.plain)
}
}
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Text("Latest articles")
.font(.custom("Raleway-Black", size: 28))
.font(.system(size: 28, weight: .bold, design: .default)) // Fallback for dynamic type
.minimumScaleFactor(0.5) // Optional: Set a minimum scale factor
.foregroundColor(.primary)
}
}
}
.task { await vm.load() }
}
}
And ...
struct FeatureArticleRow: View {
let article: ArticleSummary
var body: some View {
VStack(alignment: .leading) {
AsyncImage(url: article.thumbImageURL) { phase in
if let image = phase.image {
image
.resizable()
.aspectRatio(3/2, contentMode: .fill) // Maintain 3:2 aspect ratio
.frame(maxWidth: .infinity) // Fill the entire container width
.clipped() // Clip any overflow
} else {
Color.gray.opacity(0.2) // Placeholder
.frame(maxWidth: .infinity) // Set placeholder to fill width
.aspectRatio(3/2, contentMode: .fill) // Maintain 3:2 aspect ratio for placeholder
.clipped() // Clip any overflow
}
}
Text(article.title ?? "Untitled")
.font(Font.custom("Raleway-Bold", size: 16))
.foregroundColor(.primary)
.lineLimit(2)
.multilineTextAlignment(.leading)
Text(article.description ?? "")
//.font(.subheadline)
.font(Font.custom("Raleway-Regular", size: 15))
.foregroundColor(.secondary)
.lineLimit(5)
.multilineTextAlignment(.leading)
}
.padding(.vertical, 5)
}
}
Please refactor the code to simplify as much as possible AND fix the layout issue that I described.