Last active
August 30, 2020 00:53
-
-
Save laevandus/45dae52a0f743bd1832ea799d34bd261 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct EqualWidthPreferenceKey: PreferenceKey { | |
typealias Value = CGFloat | |
static var defaultValue: CGFloat = 0 | |
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { | |
value = nextValue() | |
} | |
} | |
struct EqualWidth: ViewModifier { | |
let width: Binding<CGFloat?> | |
func body(content: Content) -> some View { | |
content.frame(width: width.wrappedValue, alignment: .leading) | |
.background(GeometryReader { proxy in | |
Color.clear.preference(key: EqualWidthPreferenceKey.self, value: proxy.size.width) | |
}).onPreferenceChange(EqualWidthPreferenceKey.self) { (value) in | |
self.width.wrappedValue = max(self.width.wrappedValue ?? 0, value) | |
} | |
} | |
} | |
extension View { | |
func equalWidth(_ width: Binding<CGFloat?>) -> some View { | |
return modifier(EqualWidth(width: width)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment