create me a list view with images in swiftui

Generated on 8/5/2024

1 search

To create a list view with images in SwiftUI, you can follow the example provided in the "SwiftUI essentials" session. Here's a basic implementation:

import SwiftUI

struct Pet: Identifiable {
    let id = UUID()
    let name: String
    let imageName: String
}

struct ContentView: View {
    let pets = [
        Pet(name: "Whiskers", imageName: "whiskers"),
        Pet(name: "Rufus", imageName: "rufus"),
        Pet(name: "Bubbles", imageName: "bubbles")
    ]
    
    var body: some View {
        List(pets) { pet in
            HStack {
                Image(pet.imageName)
                    .resizable()
                    .frame(width: 50, height: 50)
                    .clipShape(Circle())
                Text(pet.name)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Explanation:

  1. Model: Define a Pet struct that conforms to the Identifiable protocol.
  2. Data: Create an array of Pet instances.
  3. View: Use a List to display each pet. Inside the List, use an HStack to arrange the image and text horizontally.
  4. Image: Use the Image view to display the pet's image, making it resizable and clipping it to a circle.

This example leverages the declarative nature of SwiftUI to create a list view with images and text. For more advanced customizations, you can use view modifiers and other SwiftUI features.

For more details, you can refer to the SwiftUI essentials session.