Created
February 8, 2020 20:52
-
-
Save DevAndArtist/0abe8c917c1cdebc5fd6df5f70ea8848 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
// BUG: FB7569572 | |
struct GeometrySizeKey: PreferenceKey { | |
static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) { | |
value = nextValue() | |
} | |
} | |
extension View { | |
func readGeometrySize() -> some View { | |
background( | |
GeometryReader { proxy in | |
// This view can't and won't ever be rendered. 🥳 | |
// ✅ Solution that works as a workaround, but isn't intuitive: | |
// ZStack<Never?> | |
// .init { .none } | |
// .preference(key: GeometrySizeKey.self, value: proxy.size) | |
// ❌ Solution that should work! | |
Optional<Never> | |
.none | |
.preference(key: GeometrySizeKey.self, value: proxy.size) | |
} | |
) | |
} | |
} | |
extension CGSize { | |
var max: CGFloat { | |
Swift.max(width, height) | |
} | |
} | |
struct ContentView: View { | |
@State var size: CGSize? | |
var body: some View { | |
let view = Text("Some Text") | |
.fixedSize() | |
.padding(10) | |
.readGeometrySize() | |
.frame(width: size?.max, height: size?.max) | |
.background(Circle().fill(Color.blue)) | |
.onPreferenceChange(GeometrySizeKey.self) { size in | |
self.size = size | |
} | |
return VStack { view; view } | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment