Search code examples
listlistviewcore-dataswiftuimultiple-columns

Displaying 2 Columns in SwiftUI List (pulling data from Core Data)


I have created a list in SwiftUI where it is pulling in info from 2 attributes from core data (title and month).

Works great, but I'm sure you'll agree a not very elegant solution in using string interpolation with a load of spaces in the middle to separate. Looks horrible.

How do i amend the code below to create a 2 column list with "title" going in the first column and "month" the second please (obviously in the same row).

List {
    ForEach(toDos) {
        listedToDos in
            Text ("\(listedToDos.title!)      Expires: \(listedToDos.month!)")
    }
    .onDelete(perform: deleteItems)
}

Solution

  • You can just use HStack for each row in your list.

    ForEach ... {
            
        HStack{
            Text("\(listedToDos.title!)")
            Text("Expires: \(listedToDos.month!)")
            Spacer()
        }
            
    }
    

    Give your Text items a fixed frame width if you want the columns to be left aligned. Use padding to create some whitespace.

        Text("\(listedToDos.title!)")
            .frame(width: 150, alignment: .leading)
            .padding(.leading, 10)