Home > front end >  Displaying 2 Columns in SwiftUI List (pulling data from Core Data)
Displaying 2 Columns in SwiftUI List (pulling data from Core Data)

Time:04-09

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)
}

CodePudding user response:

How about:

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

This will place the first Text on the left and the second to the right.

CodePudding user response:

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)
  • Related