I have a macOS app and i want to align a VStack of HStacks so that the label in the HStack in aligned .trailing and the other view is aligned .leading relative to all the other HStacks.
An example would be in Settings > General on Big Sur where the labels are aligned and the other controls (pickers, toggles) are aligned with each other.
How can I achieve this in SwiftUI?
An example would be in Settings > General on Big Sur where the labels are aligned and the other controls (pickers, toggles) are aligned with each other.
How can I achieve this in SwiftUI?
Code Block Swift VStack { HStack { Text("Label1") // align trailing with others Picker("Picker1", selection: $picker1) { ... } // align leading with others } Divider() HStack { Text("Label2") // align trailing with others Toggle("Toggle1", isOn: $toggle1) // align leading with others } Divider() HStack { Text("Label3") // align trailing with others Picker("Picker2", selection: $picker2) { ... } // align leading with others } }
I believe using this results in the correct alignment.
Needing to add this to the container
and this to the views in the HStacks
Code Block Swift extension HorizontalAlignment { private struct CenterLine: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { context[HorizontalAlignment.center] } } static let centerLine = Self(CenterLine.self) }
Needing to add this to the container
Code Block Swift VStack(alignment: .centerLine) { ... }
and this to the views in the HStacks
Code Block Swift .alignmentGuide(.centerLine) { $0[.trailing] } // for text label on left .alignmentGuide(.centerLine) { $0[.leading] } // for control on right