Skip to content

Instantly share code, notes, and snippets.

@pixlwave
Created October 29, 2022 20:06
Show Gist options
  • Select an option

  • Save pixlwave/6217a60fb3f87dd5a329b6ca4503c0f1 to your computer and use it in GitHub Desktop.

Select an option

Save pixlwave/6217a60fb3f87dd5a329b6ca4503c0f1 to your computer and use it in GitHub Desktop.
SwiftUI Frame Reader
import SwiftUI
extension View {
func frameReader(frame: Binding<CGRect>) -> some View {
modifier(FrameReaderModifier(frame: frame))
}
}
struct FrameReaderModifier: ViewModifier {
@Binding var frame: CGRect
func body(content: Content) -> some View {
content
.background {
GeometryReader { geometry in
Color.clear
.preference(key: FramePreferenceKey.self,
value: geometry.frame(in: .local))
}
.onPreferenceChange(FramePreferenceKey.self) { newValue in
guard frame != newValue else { return }
frame = newValue
}
}
}
}
struct FramePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
value = nextValue()
}
}
import SwiftUI
struct ContentView: View {
@State private var frame: CGRect = .zero
var body: some View {
VStack {
Text("Hello, world!")
}
.frameReader(frame: $frame)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment