Created
May 26, 2020 12:52
-
-
Save jfuellert/2e17f4b00a6f1e7897aea8880cedefc9 to your computer and use it in GitHub Desktop.
Easily read the size of a subview in SwiftUI
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
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})) | |
} | |
} |
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
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