Skip to content

Instantly share code, notes, and snippets.

@yosshi4486
Created October 20, 2024 03:29
Show Gist options
  • Save yosshi4486/8b8ab9eb4db81253cbe85e53bfcf5860 to your computer and use it in GitHub Desktop.
Save yosshi4486/8b8ab9eb4db81253cbe85e53bfcf5860 to your computer and use it in GitHub Desktop.
DynamicLabeledContentStyle
import SwiftUI
/// Use `VStack` when the Dynamic Type size is bigger than `.accessibility1`, otherwise; `HStack`.
struct DynamicLabeledContentStyle: LabeledContentStyle {
@Environment(\.dynamicTypeSize) var dynamicTypeSize
func makeBody(configuration: Configuration) -> some View {
if dynamicTypeSize.isAccessibilitySize {
VStack(alignment: .leading) {
configuration.label.foregroundStyle(.primary)
configuration.content.foregroundStyle(.secondary)
}
} else {
HStack {
configuration.label.foregroundStyle(.primary)
Spacer()
configuration.content.foregroundStyle(.secondary)
}
}
}
}
extension LabeledContentStyle where Self == DynamicLabeledContentStyle {
static var dynamic : Self { DynamicLabeledContentStyle() }
}
#Preview {
VStack {
LabeledContent {
Text("1")
} label: {
Text("Text1")
}
.labeledContentStyle(.dynamic)
.environment(\.dynamicTypeSize, .medium)
LabeledContent {
Text("2")
} label: {
Text("Text2")
}
.labeledContentStyle(.dynamic)
.environment(\.dynamicTypeSize, .accessibility1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment