Skip to content

Instantly share code, notes, and snippets.

@jfuellert
Created May 26, 2020 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfuellert/2e17f4b00a6f1e7897aea8880cedefc9 to your computer and use it in GitHub Desktop.
Save jfuellert/2e17f4b00a6f1e7897aea8880cedefc9 to your computer and use it in GitHub Desktop.
Easily read the size of a subview in SwiftUI
struct ExampleView: View {
// MARK: - Properties
@State private var size: CGSize = .zero
// MARK: - Updates
func body(content: Content) -> some View {
Text("Size of this label: \(Int(self.size.width)),\(Int(self.size.height))")
.modifier(SizeModifier({self.size = $0}))
}
}
import SwiftUI
struct SizeModifier: ViewModifier {
// MARK: - Properties
let onSize: (CGSize)->Void
// MARK: - Init
init(_ onSize: @escaping (CGSize)->Void) {
self.onSize = onSize
}
private var sizeView: some View {
GeometryReader { proxy in
Color.clear.onAppear {
self.onSize(proxy.size)
}.onPreferenceChange(SizePreferenceKey.self) {
self.onSize($0)
}
}
}
// MARK: - Updates
func body(content: Content) -> some View {
content
.background(self.sizeView)
}
}
private struct SizePreferenceKey: PreferenceKey {
// MARK: - Properties
static var defaultValue: CGSize = .zero
// MARK: - Updates
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment