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.
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:
Swift
struct RowLabel: 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:
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)
}
}