Skip to content

Instantly share code, notes, and snippets.

@timothycosta
Created July 11, 2019 03:41
Show Gist options
  • Save timothycosta/9e61418b3a4096c0f08cbe838357cabd to your computer and use it in GitHub Desktop.
Save timothycosta/9e61418b3a4096c0f08cbe838357cabd to your computer and use it in GitHub Desktop.
Find the geometry of a SwiftUI View
//
// GeometryFinder.swift
//
// Created by Timothy Costa on 2019/06/24.
// Copyright © 2019 timothycosta.com. All rights reserved.
//
import SwiftUI
struct RectPreferenceKey: PreferenceKey {
static var defaultValue: CGRect = CGRect.zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
value = nextValue()
}
}
struct GeometryFinder: View {
var coordinateSpace: CoordinateSpace = .global
var onUpdate: (CGRect) -> Void
var body: some View {
GeometryReader { proxy in
Color.clear
.preference(key: RectPreferenceKey.self, value: proxy.frame(in: self.coordinateSpace))
}
.onPreferenceChange(RectPreferenceKey.self) { value in
self.onUpdate(value)
}
}
}
struct GeometryBinder: View {
@Binding var rect: CGRect
var coordinateSpace: CoordinateSpace = .local
// old and new rects
var shouldChange: (CGRect, CGRect) -> Bool = { _,_ in return true }
//{ old,new in return old.integral != new.integral }
var body: some View {
GeometryReader { proxy in
Color.clear
.preference(key: RectPreferenceKey.self, value: proxy.frame(in: self.coordinateSpace))
}
.onPreferenceChange(RectPreferenceKey.self) { value in
if self.shouldChange(self.rect, value) {
withAnimation(nil) {
self.rect = value
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment