How to add a label to a SwiftUI Textfield in macOS

Is there a way to add a label to SwiftUI Textfield inside a SwiftUI Form so that the label is aligned with the other controls? Placeholder in textfields will disappear when you enter values so this won't help much.
All other controls have labels in macOS form with the same width so that their controls are correctly aligned. Textfield seems not to have this option. I tried several workaround like HStacks of Text and Textfields or custom alignment guides but without success.
I have the same issue - does anyone have any pointers?

The best I have come up with is an HStack with an offset:

Code Block swift
HStack {
Text("My Text")
TextField("Enter Text", text: $myText)
}
.offset(CGSize(width: -70, height: 0))

But this is pretty ugly😬. I was considering playing around with NSFormCell but I'm not sure if this is the right way to go.
I don’t know if this is what you want, but I’ve made a custom alignment guide that will align a label and a control with the centre of the view. This alignment style is used pretty much everywhere on macOS: for example, the General page in System Preferences.
Code Block Swift
extension HorizontalAlignment {
private struct CentreLine: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[HorizontalAlignment.center]
}
}
static let centreLine = Self(CentreLine.self)
}

I also made a custom Row View that handles the alignment of the label and control for you:
Code Block Swift
struct Row<Label: View, Control: View> {
private let label: Label
private let control: Control
init(label: Label, @ViewBuilder control: () -> Control) {
self.label = label
self.control = control()
}
init(@ViewBuilder control: () -> Control) where Label == EmptyView {
self.init(label: EmptyView(), control: control)
}
var body: some View {
HStack {
label.alignmentGuide(.centreLine) { $0[.trailing] }
control.alignmentGuide(.centreLine) { $0[.leading] }
}
}
}

This can then be used like this:
Code Block Swift
// need to have the alignment parameter for it to work
VStack(alignment: .centreLine) {
// with label
Row(label: Text("Username:")) {
TextField("Enter username", text: $username)
}
// without label but still aligned correctly
Row {
Toggle("Show password", isOn: $showingPassword)
}
}

How to add a label to a SwiftUI Textfield in macOS
 
 
Q