Created
August 18, 2022 09:56
-
-
Save nicohaemhouts/64d15dc909d47064f365089a6e05743a 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
/* Using GeometryReader to find out the width of the parent is problematic when the parent does not have a height and depends on its children to give it height, e.g. VStack, ScrollView, etc GeometryReader takes up all the space it can get but if the parent has no height then GeometryReader will simply not have a height and your view will not render properly. ParentWidthReader uses a widely used workaround using PreferenceKey and a GeometryReader as a background thus bypassing the height problem. | |
*/ | |
import SwiftUI | |
struct ParentWidthReader<Content>: View where Content: View { | |
typealias ContentBuilder = (CGFloat) -> Content | |
@State var width: CGFloat = .infinity | |
let content: ContentBuilder | |
init(@ViewBuilder content: @escaping ContentBuilder) { | |
self.content = content | |
} | |
var body: some View { | |
content(width) | |
EmptyView() | |
.frame(maxWidth: .infinity) | |
.background( | |
GeometryReader { | |
Color.clear | |
.preference(key: ViewWidthKey.self, value: $0.frame(in: .local).size.width) | |
} | |
) | |
.onPreferenceChange(ViewWidthKey.self) { value in | |
self.width = value | |
} | |
} | |
} | |
private struct ViewWidthKey: PreferenceKey { | |
typealias Value = CGFloat | |
static var defaultValue = CGFloat.zero | |
static func reduce(value: inout Value, nextValue: () -> Value) { | |
value += nextValue() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment