Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created July 30, 2022 04:51
Show Gist options
  • Save HarshilShah/75fc82b1d56b4eeb01fed20dae908b1e to your computer and use it in GitHub Desktop.
Save HarshilShah/75fc82b1d56b4eeb01fed20dae908b1e to your computer and use it in GitHub Desktop.
A SwiftUI extension that scales a frame using a specified dynamic type style
struct ScalingFrameModifier: ViewModifier {
@ScaledMetric var width: CGFloat
@ScaledMetric var height: CGFloat
var hasWidthSpecified: Bool
var hasHeightSpecified: Bool
var alignment: Alignment = .center
init(
width: CGFloat? = nil,
height: CGFloat? = nil,
relativeTo style: Font.TextStyle,
alignment: Alignment = .center
) {
self._width = ScaledMetric(wrappedValue: width ?? 0, relativeTo: style)
self.hasWidthSpecified = width != nil
self._height = ScaledMetric(wrappedValue: height ?? 0, relativeTo: style)
self.hasHeightSpecified = height != nil
self.alignment = alignment
}
func body(content: Content) -> some View {
content.frame(
width: hasWidthSpecified ? width : nil,
height: hasHeightSpecified ? height : nil,
alignment: alignment
)
}
}
extension View {
func frame(
width: CGFloat? = nil,
height: CGFloat? = nil,
relativeTo style: Font.TextStyle,
alignment: Alignment = .center
) -> some View {
self.modifier(ScalingFrameModifier(width: width, height: height, relativeTo: style, alignment: alignment))
}
func frame(
dimension: CGFloat?,
relativeTo style: Font.TextStyle,
alignment: Alignment = .center
) -> some View {
self.modifier(ScalingFrameModifier(width: dimension, height: dimension, relativeTo: style, alignment: alignment))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment