Skip to content

Instantly share code, notes, and snippets.

@GreatApe
Created June 30, 2019 08:37
Show Gist options
  • Save GreatApe/d0cf6fde373ad0755cfb84e588a7bc27 to your computer and use it in GitHub Desktop.
Save GreatApe/d0cf6fde373ad0755cfb84e588a7bc27 to your computer and use it in GitHub Desktop.
// Works
struct TestView1: View {
var body: some View {
SmartView {
VStack {
Text("random text")
Text("More random text")
}
}
}
}
// Doesn't work
struct TestView2: View {
var body: some View {
SmartView {
VStack {
Text("random text")
if true {
Text("More random text")
}
}
}
}
}
struct SmartView<Content: View>: View {
let content: () -> Content
@State private var contentHeight: Length = 0
var body: some View {
HStack(spacing: 0) {
Color.purple
.frame(width: 10, height: contentHeight)
content()
.background(FrameReader())
.onPreferenceChange(FramePreferenceKey.self) { self.contentHeight = $0.size.height }
Color.purple
.frame(width: 10, height: contentHeight)
}
}
}
struct FramePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
value = nextValue()
print("FramePreferenceKey: \(value)")
}
}
struct FrameReader: View {
var coordinateSpace: CoordinateSpace = .global
var body: some View {
GeometryReader { geometry in
Rectangle()
.fill(Color.clear)
.preference(key: FramePreferenceKey.self, value: geometry.frame(in: self.coordinateSpace))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment