Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Rectangle to measure its size #45

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 21 additions & 19 deletions Sources/SwiftUISupportSizing/View+MeasureSize.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import SwiftUI

private struct SizingPreferenceKey: PreferenceKey {

typealias Value = CGSize

static var defaultValue: Value = .zero

static func reduce(value: inout Value, nextValue: () -> Value) {
let next = nextValue()
value = next
}

}

extension View {

/**
Measures the receiver view size using GeometryReader.

Expand All @@ -27,16 +27,16 @@ extension View {
}

private enum GeometryReaderPreferenceKey<Projected: Equatable>: PreferenceKey {

static var defaultValue: Projected? {
return nil
}

static func reduce(value: inout Value, nextValue: () -> Projected?) {
let next = nextValue()
value = next
}

}

extension View {
Expand All @@ -55,17 +55,19 @@ extension View {
onChange: @escaping (Projected) -> Void
) -> some View {
background(
Color.clear.background(
GeometryReader(content: { proxy in
Color.clear
.preference(key: GeometryReaderPreferenceKey<Projected>.self, value: transform(proxy))
})
)
.onPreferenceChange(GeometryReaderPreferenceKey<Projected>.self) { projected in
guard let projected else { return }
onChange(projected)
}
Rectangle()
.hidden()
.background(
GeometryReader(content: { proxy in
Color.clear
.preference(key: GeometryReaderPreferenceKey<Projected>.self, value: transform(proxy))
})
)
.onPreferenceChange(GeometryReaderPreferenceKey<Projected>.self) { projected in
guard let projected else { return }
onChange(projected)
}
)
}

}
Loading