Custom alignment guide in Form

68 Views Asked by At

I want to create a SwiftUI Form with lines that have a key Text, a colon and a value Text. I want all the keys to be leading-aligned and all the values to be leading-aligned, like in this picture. Is there a way I can use a custom alignment guide or something to make sure that the value Texts all align so that there is just enough room for the longest key Text and its trailing spacing, like in the picture below?

enter image description here

1

There are 1 best solutions below

0
Mina On BEST ANSWER

The easiest way would be to use Grid (#available(iOS 16, *)).


import SwiftUI


struct Data: Identifiable {
    var id: UUID
    var title: String
    var description: String
    static var values: [Self] = [Data(id: UUID(), title: "Age", description: "42"),
                                 Data(id: UUID(), title: "Blueberry", description: "Pizza"),
                                 Data(id: UUID(), title: "Wonderful", description: "Tonight")]
}

struct ContentView: View {
    var data: [Data] = Data.values
    var body: some View {
        Grid(alignment: .leading) {
            ForEach(Data.values) { value in
                GridRow {
                    Text(value.title)
                    Text(value.description)
                }
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}


enter image description here