SwiftUI获取子View的frame
可以通过PreferenceKey获取子View的Frame, 直接上货
用了backgroundPreferenceValue,是因为onPreferenceChange会丢失信息,
struct FramePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {}
}
extension View {
func getFrame(onChange: @escaping (CGRect) -> Void) -> some View {
background(
GeometryReader { geo in
let frame = geo.frame(in: .global)
Color.clear.preference(key: FramePreferenceKey.self, value: frame)
}
)
.backgroundPreferenceValue(FramePreferenceKey.self) { frame in
return Color.clear.onAppear {
onChange(frame)
}.id(frame.maxY)
}
}
}