'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 1:[1]
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)
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wildcard |
| Solution 2 | burnsi |
