From bf96c0d841d2bc81dac0d7e28aa9ab71cd7d6c2a Mon Sep 17 00:00:00 2001 From: Enes Karaosman Date: Wed, 10 Apr 2024 09:43:29 +0300 Subject: [PATCH] feat: add readSize view modifiers --- README.md | 12 ++++++--- .../Extensions/View+Extension.swift | 25 ++++++++++++++++++- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 35d9e21..da095b2 100644 --- a/README.md +++ b/README.md @@ -16,13 +16,19 @@ Table of Contents # Extensions +```swift +TextField("Input", text: $text, axis: .vertical) + .textFieldStyle(.roundedBorder) + .readSize { + print("size: \($0)") + } +``` + ### Keyboard related modifiers (iOS only) ```swift AwesomeView() - .onKeyboardAppear { heigth in - - } + .onKeyboardAppear { heigth in } ``` ### Platform based modifiers diff --git a/Sources/SwiftUIEKtensions/Extensions/View+Extension.swift b/Sources/SwiftUIEKtensions/Extensions/View+Extension.swift index fe69de3..d88def5 100644 --- a/Sources/SwiftUIEKtensions/Extensions/View+Extension.swift +++ b/Sources/SwiftUIEKtensions/Extensions/View+Extension.swift @@ -115,9 +115,32 @@ public extension View { return self #endif } - + + /// Read view's size and bind it to `size` property + func readSize(to size: Binding) -> some View { + readSize { size.wrappedValue = $0 } + } + + /// Read view's size and take action on change + func readSize(onChange: @escaping (CGSize) -> Void) -> some View { + background( + GeometryReader { proxy in + Color.clear + .preference( + key: SizePreferenceKey.self, + value: proxy.size + ) + } + ) + .onPreferenceChange(SizePreferenceKey.self, perform: onChange) + } } +struct SizePreferenceKey: PreferenceKey { + static var defaultValue: CGSize = .zero + + static func reduce(value: inout CGSize, nextValue: () -> CGSize) {} +} public enum Platform { case iOS