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:
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 TextField
s. 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 TextField
s to expand to the size of the containing view without going over...