In SwiftUI, you can add a thumbnail image to a list in the Sandwich App using the Image view and placing it inside an HStack alongside the text. Here’s a simple way to achieve this:
Steps to Add a Thumbnail Image:
Ensure you have your image added to the Assets folder in Xcode.
Use the Image view inside your List to display the thumbnail.
Example Code:
swift
Copy
Edit
import SwiftUI
struct Sandwich: Identifiable {
let id = UUID()
let name: String
let imageName: String
}
struct ContentView: View {
let sandwiches = [
Sandwich(name: "BLT", imageName: "blt"),
Sandwich(name: "Club Sandwich", imageName: "club"),
Sandwich(name: "Grilled Cheese", imageName: "grilled_cheese")
]
var body: some View {
NavigationView {
List(sandwiches) { sandwich in
HStack {
Image(sandwich.imageName)
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
.clipShape(RoundedRectangle(cornerRadius: 8))
Text(sandwich.name)
.font(.headline)
}
}
.navigationTitle("Sandwich List")
}
}
}
Explanation:
The Sandwich struct represents each sandwich with a name and an image name.
The List displays sandwiches with an HStack, where:
The Image is resizable, scaled to fit, and clipped with a rounded rectangle.
The Text shows the sandwich name.
Ensure that the images (e.g., blt, club, grilled_cheese) are added to Assets.xcassets in your project.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: