Last active
May 19, 2023 23:22
-
-
Save StewartLynch/6343adcabc99f3798f79377843f36cf3 to your computer and use it in GitHub Desktop.
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
// Sample Use | |
struct ContentView: View { | |
@State private var size: CGSize = .zero | |
var body: some View { | |
VStack { | |
Text("\(size.width)") | |
Text("Hello World") | |
.getCGSize($size) | |
} | |
.padding() | |
} | |
} | |
// PreferenceKey | |
struct CGSizeKey: PreferenceKey { | |
static var defaultValue = CGSize.zero | |
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { | |
value = nextValue() | |
} | |
} | |
extension View { | |
func getCGSize(_ viewSize: Binding<CGSize>) -> some View { | |
background( | |
GeometryReader { proxy in | |
Color.clear | |
.preference(key: CGSizeKey.self, value: proxy.size) | |
} | |
.onPreferenceChange(CGSizeKey.self) { value in | |
viewSize.wrappedValue = value | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment