Search code examples
iosswiftuiuikitswiftui-list

Implementing SwiftUI list items aligned with image


Is there some tricky way to implement a list in SwiftUI with a set of 'continuous' images on its left perfectly aligned with the text?

I am not looking for code, but hints on ways to achieve this.

Enter image description here

Enter image description here


Solution

  • Looking at the linked post, they are using a VStack & a ScrollView. However, this can be done using a List:

    Preview

    struct TestView: View {
        var body: some View {
            List {
                ForEach(["pencil", "ruler", "book"], id: \.self) { item in
                    HStack(alignment: .top) {
                        VStack(spacing: 0) {
                            Image(systemName: item)
                                .foregroundColor(.white)
                                .frame(width: 35, height: 35)
                                .background(Color.blue)
                                .clipShape(RoundedRectangle(cornerRadius: 12))
                            Rectangle()
                                .fill(Color.blue.opacity(0.5))
                                .frame(width: 5, height: 50) //you can remove the height to make it dynamic & use padding for the spacing.
                        }
                        VStack(alignment: .leading) {
                            Text("Day 1")
                                .font(.title3)
                                .fontWeight(.bold)
                            Text("This is a long text as for testing the layout of the cell.")
                                .fontWeight(.medium)
                                .opacity(0.7)
                        }
                    }
                }.listRowInsets(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15))
                .listRowSeparator(.hidden)
            }.listStyle(.plain)
        }
    }