Last active
June 6, 2024 12:32
-
-
Save buh/0ce2967fe21de14d5052af6e05c25d37 to your computer and use it in GitHub Desktop.
SwiftUI view extension to read the frame and bind it to the reader.
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
// | |
// Created by Alexey Bukhtin on 26/03/2021. | |
// | |
import SwiftUI | |
extension View { | |
/// Reads the view frame and bind it to the reader. | |
/// - Parameters: | |
/// - coordinateSpace: a coordinate space for the geometry reader. | |
/// - reader: a reader of the view frame. | |
func readFrame(in coordinateSpace: CoordinateSpace = .global, | |
for reader: Binding<CGRect>) -> some View { | |
readFrame(in: coordinateSpace) { value in | |
reader.wrappedValue = value | |
} | |
} | |
/// Reads the view frame and send it to the reader. | |
/// - Parameters: | |
/// - coordinateSpace: a coordinate space for the geometry reader. | |
/// - reader: a reader of the view frame. | |
func readFrame(in coordinateSpace: CoordinateSpace = .global, | |
for reader: @escaping (CGRect) -> Void) -> some View { | |
background( | |
GeometryReader { geometryProxy in | |
Color.clear | |
.preference( | |
key: FramePreferenceKey.self, | |
value: geometryProxy.frame(in: coordinateSpace) | |
) | |
.onPreferenceChange(FramePreferenceKey.self, perform: reader) | |
} | |
) | |
} | |
} | |
private struct FramePreferenceKey: PreferenceKey { | |
static var defaultValue = CGRect.zero | |
static func reduce(value: inout CGRect, nextValue: () -> CGRect) { | |
value = nextValue() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great help!👍🏻