Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI relative frame
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
struct RelativeSizeModifier: ViewModifier {
let percentWidth: CGFloat
@State private var contentSize: CGSize = .zero
func body(content: Content) -> some View {
GeometryReader { geometry1 in
content
.frame(width: geometry1.size.width * percentWidth)
.background(
GeometryReader { geometry2 in
Color.green
.preference(key: SizePreferenceKey.self, value: geometry2.size)
}
)
.frame(maxWidth: .infinity)
}
.frame(height: contentSize.height)
.onPreferenceChange(SizePreferenceKey.self) { self.contentSize = $0 }
}
}
extension View {
func relative(width: CGFloat) -> some View {
self.modifier(RelativeSizeModifier(percentWidth: width))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment