Created
April 28, 2024 18:20
-
-
Save GeorgeElsham/0d9c5102b2cf65bb299c716b050cb89c to your computer and use it in GitHub Desktop.
Read view size
This file contains 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
import SwiftUI | |
extension View { | |
func readSize(_ reader: @escaping (CGSize) -> Void) -> some View { | |
background { | |
GeometryReader { geo in | |
Color.clear.preference(key: SizeKey.self, value: geo.size) | |
} | |
.onPreferenceChange(SizeKey.self) { size in | |
reader(size) | |
} | |
} | |
} | |
} | |
private enum SizeKey: PreferenceKey { | |
static let defaultValue: CGSize = .zero | |
static func reduce(value: inout Value, nextValue: () -> Value) { | |
value = nextValue() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment