Layout in SwiftUI with horizontal and vertical alignment

后端 未结 6 2075
别跟我提以往
别跟我提以往 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条回答
  •  渐次进展
    2021-02-04 09:42

    Looks like this will work:

    extension HorizontalAlignment {
        private enum MyAlignment: AlignmentID {
            static func defaultValue(in context: ViewDimensions) -> Length {
                context[.trailing]
            }
        }
        static let myAlignmentGuide = HorizontalAlignment(MyAlignment.self)
    }
    
    struct ContentView : View {
        @State var username: String = ""
        @State var email: String = ""
        @State var password: String = ""
    
        var body: some View {
            VStack(alignment: .myAlignmentGuide) {
                HStack {
                    Text("Username").alignmentGuide(.myAlignmentGuide, computeValue: { d in d[.trailing] })
                    TextField($username)
                        .textFieldStyle(.roundedBorder)
                        .frame(maxWidth: 200)
                }
                HStack {
                    Text("Email")
                        .alignmentGuide(.myAlignmentGuide, computeValue: { d in d[.trailing] })
                    TextField($email)
                        .textFieldStyle(.roundedBorder)
                        .frame(maxWidth: 200)
                }
                HStack {
                    Text("Password")
                        .alignmentGuide(.myAlignmentGuide, computeValue: { d in d[.trailing] })
                    TextField($password)
                        .textFieldStyle(.roundedBorder)
                        .frame(maxWidth: 200)
                }
            }
        }
    }
    

    With that code, I am able to achieve this layout:

    The caveat here is that I had to specify a max width for the TextFields. Left unconstrained, the layout system described in the WWDC talk I linked in the comments retrieves a size for the TextField prior to alignment happening, causing the TextField for email to extend past the end of the other two. I'm not sure how to address this in a way that will allow the TextFields to expand to the size of the containing view without going over...

提交回复
热议问题