'How to align element in different row in SwiftUI?

enter image description here

I want to create a list view with a text of name(which may be different length) and a text of version, and I want all text of version is aligned,how to realize it in SwiftUI?

Code of the rows

struct ComponentRow: View {
    @EnvironmentObject var component: Component
    var body: some View {
        HStack {
            Text(String(randomStringWithLength(len:Int(arc4random()%20+10))))
            TextField("版本号", text: $component.version)
        }
    }
}

The list is

List {
                ForEach(configure.components) { component in
                    ComponentRow().environmentObject(component)
                }
            }


Solution 1:[1]

You can use GeometryReader to get the full width and then give the single elements e.g. 2/3 and 1/3 of that space:

var body: some View {
    List {
        ForEach(0..<50) { component in
            GeometryReader { geo in
            HStack {
                Text(title)
                    .lineLimit(1)
                    .padding(.trailing)
                    .frame(width: geo.size.width / 3 * 2, alignment: .leading)
                
                TextField(number, text: $input) // dummy only!
                    .frame(width: geo.size.width / 3 * 1, alignment: .leading)
            }
        }
    }
    }
    .listStyle(.plain)
    .padding()
}

or use LazyVGrid, where you can also use other column sizes:

struct ContentView: View {

    let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 2)
    
    var body: some View {
        List {
            ForEach(0..<50) { component in
                LazyVGrid(columns: columns, alignment: .leading) {
                    Text(title)
                        .lineLimit(1)
                        .padding(.trailing)
                    Text(number)
                }
            }
        }
        .listStyle(.plain)
        .padding()
    }
    
    
    var title: String {
        String("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec,".prefix(Int.random(in: 3..<30)))
    }
    var number: String {
        String("1243568743584375872345734289758342759872435987".prefix(Int.random(in: 0..<10)))
    }
}

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