-
Notifications
You must be signed in to change notification settings - Fork 9
/
Measure+Position.swift
52 lines (46 loc) · 1.33 KB
/
Measure+Position.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Foundation
extension View {
func measurePosition(_ id: AnyHashable?, coordSpace: String) -> some View {
background {
if let id {
GeometryReader { proxy in
Color.clear
.preference(key: PositionsPreferenceKey.self, value: [id: proxy.frame(in: .named(coordSpace))])
}
} else {
Color.clear
}
}
}
}
// MARK: - PositionsPreferenceKey
enum PositionsPreferenceKey: PreferenceKey {
static var defaultValue: [AnyHashable: CGRect] = [:]
static func reduce(value: inout [AnyHashable: CGRect], nextValue: () -> [AnyHashable: CGRect]) {
value.merge(nextValue()) { $1 }
}
}
extension View {
func measureSize(_ id: AnyHashable) -> some View {
background {
GeometryReader { proxy in
Color.clear
.preference(key: PositionsPreferenceKey.self, value: [id: proxy.frame(in: .local)])
}
}
}
func onReadPosition(_ id: AnyHashable, action: @escaping (CGRect) -> Void) -> some View {
onPreferenceChange(PositionsPreferenceKey.self) { positions in
if let position = positions[id] {
action(position)
}
}
}
func onReadSizes(_ id1: AnyHashable, _ id2: AnyHashable, action: @escaping (CGSize, CGSize) -> Void) -> some View {
onPreferenceChange(PositionsPreferenceKey.self) { positions in
if let size1 = positions[id1]?.size, let size2 = positions[id2]?.size {
action(size1, size2)
}
}
}
}