Layout in SwiftUI with horizontal and vertical alignment

后端 未结 6 2076
别跟我提以往
别跟我提以往 2021-02-04 09:11

I\'m trying to accomplish this layout

If I try HStack wrapped in VStack, I get this:

If I try VStack wrapped in HStack, I get this:

6条回答
  •  猫巷女王i
    2021-02-04 09:47

    You need to add fixed width and leading alignment. I've tested in Xcode 11.1 it's ok.

    struct TextInputWithLabelDemo: View {
        @State var text = ""
        let labels = ["Username", "Email", "Password"]
    
        var body: some View {
            VStack {
                ForEach(labels, id: \.self) { label in
                    HStack {
                        Text(label).frame(width: 100, alignment: .leading)
                        TextField(label, text: self.$text)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                    }
                }
                .padding(.horizontal)
                .fixedSize(horizontal: false, vertical: true)
            }
        }
    }
    

    Below You can see what the issue when we use different VStack for Text and TextField. See more info here

    Updated 16 Oct 2019

    A closer inspection of Texts and TextFields you can notice that they have different heights and it effects the positions of Texts relative to TextFields as you can see on the right side of the screenshot that Password Text is higher relative to Password TextField than the Username Text relative to Username TextField. I gave three ways to resolve this issue here

提交回复
热议问题