Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Last active August 2, 2020 17:43
Show Gist options
  • Save mattyoung/8f685183cfc8ca0a620bfdd508e31fcb to your computer and use it in GitHub Desktop.
Save mattyoung/8f685183cfc8ca0a620bfdd508e31fcb to your computer and use it in GitHub Desktop.
//
// TextLabelViewForSeanHeber.swift
// NewWorld12
//
// Created by Matthew on 8/1/20.
//
// https://twitter.com/BigZaphod/status/1289674767684046848
import SwiftUI
struct SHPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout Value, nextValue: () -> Value) {
value = max(value, nextValue())
}
}
struct SHModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.fixedSize()
.background(
GeometryReader {
Color.clear
.preference(key: SHPreferenceKey.self, value: $0.size.width)
}
)
}
}
struct SHView<Title: View, Body: View>: View {
let titleView: Title
let bodyView: Body
@State var viewWidth: CGFloat = 0
init(@ViewBuilder titleView: () -> Title, @ViewBuilder bodyView: () -> Body) {
self.titleView = titleView()
self.bodyView = bodyView()
}
var body: some View {
VStack(alignment: .leading) {
titleView
.modifier(SHModifier())
// force the view width to expand to full width of parent
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.black)
bodyView
.modifier(SHModifier())
}
.onPreferenceChange(SHPreferenceKey.self) { viewWidth = $0 }
.frame(width: viewWidth)
.background(Color.red)
.cornerRadius(15)
}
}
struct TextLabelViewForSeanHeberDemo: View {
var body: some View {
VStack(alignment: .leading, spacing: 5) {
SHView {
Text("Title Here")
.foregroundColor(.white)
.font(.title)
}
bodyView: {
Text("Text something with a long string.")
.bold()
}
SHView {
Text("Something Else")
.foregroundColor(.white)
.font(.title)
}
bodyView: {
Text("Lorem Ipsum, Lorem Ipsum")
.bold()
}
SHView {
Text("The title is longer than body")
.foregroundColor(.white)
.font(.title)
}
bodyView: {
Text("Lorem Ipsum, Lorem Ipsum")
.bold()
}
}
}
}
struct TextLabelViewForSeanHeber_Previews: PreviewProvider {
static var previews: some View {
TextLabelViewForSeanHeberDemo()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment