Skip to content

Instantly share code, notes, and snippets.

@IntegerOverlord
Created December 17, 2023 22:36
Show Gist options
  • Save IntegerOverlord/c285bdbaeb16bcae3fc14a363d3c0a73 to your computer and use it in GitHub Desktop.
Save IntegerOverlord/c285bdbaeb16bcae3fc14a363d3c0a73 to your computer and use it in GitHub Desktop.
import SwiftUI
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}
public extension View {
func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
self
.background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
func readSize(andUpdate value: Binding<CGSize>) -> some View {
self.readSize { size in
value.wrappedValue = size
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment