Is there any way to get the size of a child view in SwiftUI?
I\'m basically looking to do the UIKit equivalent of:
Here's a reusable variant of the accepted answer:
protocol SizeReaderKey: PreferenceKey where Value == CGSize {}
extension SizeReaderKey {
static func reduce(value _: inout CGSize, nextValue: () -> CGSize) {
_ = nextValue()
}
}
struct SizeReader: ViewModifier {
func body(content: Content) -> some View {
content
.background(
GeometryReader { geo in
Color.clear
.preference(key: Key.self, value: geo.size)
}
)
}
}
extension View {
func onSizeChanged(
_ key: Key.Type,
perform action: @escaping (CGSize) -> Void) -> some View
{
self
.modifier(SizeReader())
.onPreferenceChange(key) { value in
action(value)
}
}
}
Usage:
struct Example: View {
var body: some View {
Text("Hello, World!")
.onSizeChanged(CustomViewSizeKey.self) { size in
print("size: \(size)")
}
}
struct CustomViewSize: SizePreferenceKey {
static var defaultValue: CGSize = .zero
}
}