Created
July 11, 2019 03:41
-
-
Save timothycosta/9e61418b3a4096c0f08cbe838357cabd to your computer and use it in GitHub Desktop.
Find the geometry of a SwiftUI View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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