Skip to content

Instantly share code, notes, and snippets.

@GeorgeElsham
Last active August 14, 2022 12:51
Show Gist options
  • Save GeorgeElsham/49967052965db24b8a9b4649aefb5bc9 to your computer and use it in GitHub Desktop.
Save GeorgeElsham/49967052965db24b8a9b4649aefb5bc9 to your computer and use it in GitHub Desktop.
struct ContentView: View {
@State private var height: CGFloat = 0
var body: some View {
HStack {
CustomButton("Directions", imageName: "arrow.triangle.turn.up.right.circle.fill") {
//
}
.buttonStyle(.borderedProminent)
CustomButton("Call", imageName: "phone.fill") {
//
}
.buttonStyle(.bordered)
CustomButton("Website", imageName: "safari.fill") {
//
}
.buttonStyle(.bordered)
CustomButton("More", imageName: "ellipsis") {
//
}
.buttonStyle(.bordered)
}
.frame(height: height)
.onPreferenceChange(HeightKey.self) { height in
self.height = height
}
.padding()
}
}
struct CustomButton: View {
private let title: String
private let imageName: String
private let action: () -> Void
init(_ title: String, imageName: String, action: @escaping () -> Void) {
self.title = title
self.imageName = imageName
self.action = action
}
var body: some View {
Button(action: action) {
VStack(spacing: 5) {
Image(systemName: imageName)
.frame(maxHeight: .infinity)
Text(title)
.font(.caption)
}
.frame(maxWidth: .infinity)
}
.background(
GeometryReader { geo in
Color.clear.preference(
key: HeightKey.self,
value: geo.size.height
)
}
)
}
}
struct HeightKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment