Skip to content

Instantly share code, notes, and snippets.

@hhhello0507
Created March 25, 2025 12:43
Show Gist options
  • Save hhhello0507/8cf9e28da9e86d8dc8122a42dbf01f3b to your computer and use it in GitHub Desktop.
Save hhhello0507/8cf9e28da9e86d8dc8122a42dbf01f3b to your computer and use it in GitHub Desktop.
import SwiftUI
public extension View {
@ViewBuilder
func onReadSize(_ perform: @escaping (CGSize) -> Void) -> some View {
self.customBackground {
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
}
.onPreferenceChange(SizePreferenceKey.self, perform: perform)
}
@ViewBuilder
func customBackground<V: View>(alignment: Alignment = .center, @ViewBuilder content: () -> V) -> some View {
self.background(alignment: alignment, content: content)
}
}
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment