Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding shapes in List row of SwiftUI

I am trying to create a List View where rows looks like this:

enter image description here

However, I am unable to align the Circle on the leading side. Tried using Spacer(), HStack within VStack, it just doesn't work. Here's my code and its output.

struct PeopleView: View {
    
    let people = ["Adam", "James"]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(people, id: \.self) { person in
                    HStack {
                        Circle()
                        VStack {
                            Text("\(person)")
                        }
                    }
                }
            }
            .navigationBarTitle("People", displayMode: .inline)
        }
    }
}

tui

like image 532
Baqir Khan Avatar asked Sep 13 '25 11:09

Baqir Khan


2 Answers

Actually you don't need shape itself in this case, but only as a mask to visually present text in circle.

So the solution can be like following

demo

HStack {
    Text(person.prefix(2).uppercased()).bold()
        .foregroundColor(.white)
        .padding()
        .background(Color.red)
        .mask(Circle())          // << shaping text !!

    Spacer()
    VStack {
        Text("\(person)")
    }
}
like image 67
Asperi Avatar answered Sep 15 '25 02:09

Asperi


Some views in SwiftUI fill all available space. Such views are shapes, colors, spacers, dividers, and GeometryReader.

Your Circle is a shape and it behaves similarly like a Spacer (in terms of filling space).

If you replace Circle with an image of a circle it will work:

ForEach(people, id: \.self) { person in
    HStack {
        Image(systemName: "circle.fill")
            .imageScale(.large)
        Spacer()
        VStack {
            Text("\(person)")
        }
    }
}
like image 39
pawello2222 Avatar answered Sep 15 '25 03:09

pawello2222