Last active
May 15, 2022 07:54
-
-
Save mishimay/bf27c67c662102095392a330738b15f3 to your computer and use it in GitHub Desktop.
How to get child view size in SwiftUI View
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 ContentView: View { | |
@State var size: CGSize = .zero | |
var body: some View { | |
VStack { | |
Text(size.debugDescription) | |
ChildView() | |
} | |
.onPreferenceChange(SizePreferenceKey.self) { | |
size = $0 | |
} | |
} | |
} | |
struct ChildView: View { | |
var body: some View { | |
Text("Message") | |
.background(GeometryReader { geometry in | |
Color.clear.preference( | |
key: SizePreferenceKey.self, | |
value: geometry.size | |
) | |
}) | |
} | |
} | |
struct SizePreferenceKey: PreferenceKey { | |
static var defaultValue: CGSize = .zero | |
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { | |
// If there are if statements in the target view, nextValue() can be (0, 0) | |
value = value.width * value.height > nextValue().width * nextValue().height ? value : nextValue() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment