Skip to content

Instantly share code, notes, and snippets.

@cliss
Created February 2, 2021 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliss/aecfcba088fa051ef1d4da521b694070 to your computer and use it in GitHub Desktop.
Save cliss/aecfcba088fa051ef1d4da521b694070 to your computer and use it in GitHub Desktop.
Matching Heights Techniques
import UIKit
import SwiftUI
import PlaygroundSupport
/* *****************************************
* GeometryReader with PreferenceKey
* *****************************************/
struct HeightPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
let next = nextValue()
print("\(value) with new value \(next) → \(max(value, next))")
value = max(value, next)
}
}
struct GeometryReaderView: View {
@State private var pillsMaxHeight: CGFloat?
var body: some View {
VStack {
HStack(spacing: 15) {
VStack {
Text("Some Headline")
.font(.headline)
.underline()
.padding(.bottom, 5)
Text("This is some text that is quite a bit longer than what's in the other box.")
}
.background(GeometryReader { proxy in
Color.clear.preference(key: HeightPreferenceKey.self,
value: proxy.size.height)
})
.frame(height: self.pillsMaxHeight)
.padding(.all)
.background(RoundedRectangle(cornerRadius: 5.0).fill(Color.green))
VStack {
Text("Another Headline")
.font(.headline)
.underline()
.padding(.bottom, 5)
Text("Considerably shorter text here.")
}
.background(GeometryReader { proxy in
Color.clear.preference(key: HeightPreferenceKey.self,
value: proxy.size.height)
})
.frame(height: self.pillsMaxHeight)
.padding(.all)
.background(RoundedRectangle(cornerRadius: 5.0).fill(Color.green))
}
.onPreferenceChange(HeightPreferenceKey.self) {
self.pillsMaxHeight = $0
}
}
}
}
/* *****************************************
* Frame-based View with Fixed Size
* *****************************************/
struct FrameView: View {
var body: some View {
HStack {
VStack {
Text("Short Headline")
.bold()
.underline()
.padding(.bottom, 5)
Text("This is some text that is quite a bit longer than what's in the other box.")
}
.padding()
.frame(maxHeight: .infinity, alignment: .top)
.background(Color.green)
VStack {
Text("Another Headline")
.bold()
.underline()
.padding(.bottom, 5)
Text("Shorter text goes here.")
}
.padding()
.frame(maxHeight: .infinity, alignment: .top)
.background(Color.green)
}
.fixedSize(horizontal: false, vertical: true)
.padding()
}
}
// Swap the below to see the alternate version.
//
// However, the GeometryReaderView() is causing
// SIGABRT for reasons I don't understand. 🤷🏻‍♂️
//PlaygroundPage.current.setLiveView(GeometryReaderView().frame(width: 500, height: 500))
PlaygroundPage.current.setLiveView(FrameView().frame(width: 500, height: 500))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment