Reputation: 1155
I'm trying to get items inside a list to line up in a specific way.
List {
HStack {
Text("1.")
Text("Item 1")
}
HStack {
Text("Item 2")
}
}
That winds up looking like this:
1. Item 1
Item 2
What I'd like is to line up, in this example, "Item 1" and "Item 2":
1. Item 1
Item 2
That is, the "item" parts all line up whether they have a list marker or not, or if they have list markers of different lengths (number 1. lines up with 100.)
I tried making a custom alignment guide as seen here but these don't seem to be respected inside a List
--- it works fine if I make the AlignmentGuide
and put it all in a VStack
, but I need list behavior.
(I could fake this by getting rid of the HStacks
and doing Text("1.\tItem 1")
and Text("\tItem 2")
. The tab stops would make everything line up, but I need to apply different formatting to the list marker and the list item (bolding, color, etc.), so they need to be discrete Text
elements.)
Any ideas would be appreciated.
Upvotes: 4
Views: 2403
Reputation: 36620
import SwiftUI
struct ContentView: View {
var body: some View {
List {
HStack {
Text("1.").frame(width: 20.0, height: nil, alignment: .leading)
Text("Item 1")
}
HStack {
Text("Item 2")
.padding(EdgeInsets(top: 0, leading: 28, bottom: 0, trailing: 0))
}
HStack {
Text("2.").frame(width: 20.0, height: nil, alignment: .leading)
Text("Item 3")
}
HStack {
Text("Item 4")
.padding(EdgeInsets(top: 0, leading: 28, bottom: 0, trailing: 0))
}
}
}
}
** Updated **
Hope this is closer to what you are looking for.
By specifying a frame around the leading value, you can control its size so it should work for your need to modify the text value.
It should also be possible to calculate values for the purpose of setting the frame and padding, but these hard coded values should achieve the immediate effect.
Upvotes: 2