Skip to content

Instantly share code, notes, and snippets.

@markbattistella
Last active October 28, 2022 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markbattistella/1a75913b532a09aef821d211774c02f1 to your computer and use it in GitHub Desktop.
Save markbattistella/1a75913b532a09aef821d211774c02f1 to your computer and use it in GitHub Desktop.
Retrieve the size of an element within SwiftUI
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ContentView: View {
@State var hStackSize: CGSize = .zero
var body: some View {
HStack {
Image(systemName: "tray.fill")
Text("Beep boop")
}
.font(.title)
.background(Color.pink)
.getSize { size in
hStackSize = size
}
.onChange(of: hStackSize) { newValue in
print("New HStack Size is: \(hStackSize)")
}
}
}
struct SizeReader: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
extension View {
func getSize(size: @escaping (CGSize) -> Void) -> some View {
return self
.background(
GeometryReader { geometry in
Color.clear
.preference(key: SizeReader.self, value: geometry.size)
.onPreferenceChange(SizeReader.self) { value in size(value) }
}.hidden()
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment