-
-
Save garsdle/8b4f3e527e12eda36d854aed91b0635f to your computer and use it in GitHub Desktop.
SwiftUI relative frame
This file contains hidden or 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 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