Last active
October 28, 2022 23:22
-
-
Save markbattistella/1a75913b532a09aef821d211774c02f1 to your computer and use it in GitHub Desktop.
Retrieve the size of an element within SwiftUI
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
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