Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Last active August 11, 2021 12:05
Show Gist options
  • Save kirsteins/51bbb5f187987b3ec034096f265b68f2 to your computer and use it in GitHub Desktop.
Save kirsteins/51bbb5f187987b3ec034096f265b68f2 to your computer and use it in GitHub Desktop.
Toggles and labels aligned at fixed size
struct ToggleWidthPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
extension View {
func measureToggle() -> some View {
self.background(GeometryReader { geometry in
Color.clear.preference(
key: ToggleWidthPreferenceKey.self,
value: geometry.size.width
)
})
}
}
struct ContentView: View {
@State var condition1 = false
@State var condition2 = false
@State var toggleMaxWidth: CGFloat?
var body: some View {
VStack(alignment: .leading) {
Toggle(isOn: $condition1) {
Text("Condition One")
}
.measureToggle()
.frame(width: toggleMaxWidth)
Toggle(isOn: $condition2) {
Text("Condition Two Two")
}
.measureToggle()
.frame(width: toggleMaxWidth)
}
.padding()
.border(Color.blue)
.fixedSize()
.onPreferenceChange(ToggleWidthPreferenceKey.self) {
toggleMaxWidth = $0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment